1👍
It’s definitely possible to subclass existing django.contrib.auth views, but I think writing your own ajax-specific view is a better approach and it only takes a few lines of code anyway.
Here is what it may look like:
@login_required
def change_password(request):
if request.is_ajax():
try:
# extract new_password value from POST/JSON here, then
user = User.objects.get(username=request.user.username)
except User.DoesNotExist:
return HttpResponse("USER_NOT_FOUND")
else
user.set_password(new_password)
user.save()
return HttpResponse("OK")
else:
return HttpResponse(status = 400)
1👍
If I were to choose, I would also go with implementing a separate view for your purpose.
Ideally, if django.contrib.auth
was re-implemented in class-based views, you would be able to reuse the logic of changing password and write your code only for the part that returns a response that is more appropriate for AJAX. But too bad we don’t have the luxury of that, at least not for django 1.3 or prior.
But to answer your question, yes, there is an alternative (or hack I would call it) that enables you to reuse the view in django.contrib.auth
. Assuming you are using jQuery, at submitting the change password form, you would make a AJAX POST request to the server and expect html in return (illustrated below). The returned html is the same as the one you would get when using non-AJAX POST.
var post_url = $form.attr("action");
$.ajax({
type: "POST",
url: post_url,
data: $form.serialize()
}).done(function(html) {
// check the html and use that to determine what message to prompt back to your user
});
- [Answered ]-Django: How to you organise static pages in apps?
- [Answered ]-Vagrant 'paver devstack lms' Starting server: Command "python setup.py egg_info" failed with error code 1
- [Answered ]-How to setup a VPS with Django, Nginx, Gunicorn, Postgres and then properly deploy a Django application to it?
- [Answered ]-Order of select_related in chain
- [Answered ]-Asynchronously update page with data that are stored by middleware