Changing Password in Django using Jquery/Ajax

I posted about this not so long ago without using JQuery/Ajax, here is the link.This time, with different approach and much easier.All you need to do is create function in views.py then use it in urls.py and call the URL using Ajax.

 HTML:

<form action="/change_pw/" method="post" id="frmChangePW">
  {% csrf_token %}
  <div class="form-group">
    <label for="id_old_password">Old Password:</label>
    <input class="form-control" id="id_old_password" name="old_password" type="password" placeholder="Old Password" autofocus="">
  </div>
  <div class="form-group">
    <label for="id_new_password">New Password:
      <input class="form-control" id="id_new_password" name="new_password" placeholder="New Password" type="password">
    </label>
    <label for="id_re_new_password">Re-type New Password:
      <input class="form-control" id="id_re_new_password" name="re_new_password" placeholder="Re-type New Password" type="password">
    </label>
  </div>
  <input type="submit" id="btnUpdate" value="Update" class="btn btn-primary">
</form>

JQuery:

var frmPW = $('#frmChangePW');
frmPW.submit(function() {
  $.ajax({
    type: frmPW.attr('method'),
    url: frmPW.attr('action'),
    data: frmPW.serialize(),
    success: function(resp) {
      $("#respp").html('<strong><p class="text-info">' + resp + '</p></strong>').show().fadeOut(3000);
    },
    error: function() {
      $("#respp").html('<strong><p class="text-danger">Error!</p></strong>').show().fadeOut(3000);
    }
  });
  return false;
});


urls.py:

 url(r'^change_pw/$', '<app_name>.views.change_pw'),

views.py:

@login_required
def change_pw(request):
    uname = request.user.username
    message = {}
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        retype_new_password = request.POST.get('re_new_password')
        user = authenticate(username=uname, password=old_password)
        if user is not None:
            if new_password == retype_new_password and new_password != '':
                u = User.objects.get(username=uname)
                u.set_password(new_password)
                u.save()
                message = 'Successfully Changed the Password.'
            else:
                message = 'Invalid Passwords!'
        else:
            message = 'Invalid Password!'
    return HttpResponse(json.dumps(message), content_type='application/json')

Screenshot:

Popular posts from this blog

Set table width to 100% on PDF export in Datatables

Add/Subtract Single Digit Number in Assembly Language