Search code examples
pythondjangohashchange-password

create a profile page with django


I created a profile page with django to let users change their information that I gave in sing up form . (such as name, email, password)

I have two problem on password field :

1 - when user insert a password in text field, it's submitted in raw format, and I need django user's table format

<algorithm>$<iterations>$<salt>$<hash>

my view for profile page :

def user_profile(request):
    current_user = request.user
    form = UserProfileForm(request.POST or None, instance=current_user)
    if request.POST:
        if form.is_valid():
             # pwd = form.cleaned_data['password']
             # form_obj = form.save(commit=False)
             # form_obj.password = make_password(pwd)
             form.save()
             message = "saved successfully"
             return render(request, 'Profile.html', {'form':form, 'message':message}, context_instance=RequestContext(request))

    return render_to_response('Profile.html', {
        'form': form,
    }, context_instance=RequestContext(request))

as you can see in comments, I used make_password function to hash password and it works fine BUT after submitting page, user can't go to other pages and need re-login ... why ?!

2 - when the profile page shows to user, it's filled with current informations in database, and password is also in the above format (hash) and if user submit the form, without any change in password field, it's password changed (it sends hash one and hash it again !)

how can I solve this problems and make a simple working profile page in django ? (I really don't like it's own admin panel ! it doesn't look nice !)


Solution

  • From the documentation:

    Changing a user’s password will log out all their sessions if the SessionAuthenticationMiddleware is enabled.

    So you have to use update_session_auth_hash(request, user)

    For more info, see https://docs.djangoproject.com/en/1.9/topics/auth/default/#session-invalidation-on-password-change

    Regarding the password field being pre-populated: you should set the field as a passwordInput which, by default, is not pre-populated, see https://docs.djangoproject.com/en/1.9/ref/forms/widgets/#django.forms.PasswordInput