1

I am changing the password if the current user is logged in.

views.py:

def change_password(request,pk=None):
    user = MyUser.objects.get(pk=pk)
    if request.method == "POST":
        form = PasswordChangeForm(user=user, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            context = {
                'form': form,
                'title': _('Password change'),
            }
            return render(request, "nurse/change_password.html")

    else:
        form = PasswordChangeForm(user=user)
    context = {
        'form': form,
        'title': _('Password change'),
    }
    return render(request,"nurse/change_password.html")

The function is working fine, but after this function call, I am not getting user.id in my html file.

What am I doing wrong?

zondo
  • 19,901
  • 8
  • 44
  • 83
Vardan
  • 454
  • 1
  • 5
  • 18
  • Possible duplicate of [django user logged out after password change](http://stackoverflow.com/questions/30821795/django-user-logged-out-after-password-change) – Sayse Jun 14 '16 at 10:40
  • Just realised you already update the hash, in which case, you should update your [existing question](http://stackoverflow.com/q/37807657/1324033) with updated information. – Sayse Jun 14 '16 at 10:43
  • what information should i add more? – Vardan Jun 14 '16 at 10:48
  • Django [comes with authentication views](https://docs.djangoproject.com/en/1.9/topics/auth/default/#module-django.contrib.auth.views), including changing password. It would probably be easier to use that rather than write your own. – Alasdair Jun 14 '16 at 10:50
  • I would start by addressing Alasdair's comment in your last question. You only ever include the `user_id` in a post request if the form is valid. – Sayse Jun 14 '16 at 10:51
  • I've a function that does exactly this and is exactly the same as yours (although I called my form 'pass_form' instead of 'form') with the one exception I do not use `user = MyUser.objects.get(pk=pk)` but use `request.user`. Perhaps you've an issue here? – HenryM Jun 14 '16 at 12:04
  • Hi @HenryM your solution is working but for current page. Means i am getting user_id after clicking change password but i am not getting it after i migrate to any other page. – Vardan Jun 15 '16 at 08:21
  • @Vardan, I'm stuck. Are you using `user = MyUser.objects.get(pk=pk)` on your other pages. I can only assume you've a problem here somewhere. If so, how is MyUser defined, or more specifically within models.py is it defined with a field something like `user = models.OneToOneField(User, on_delete=models.CASCADE)`. This is what I've done and I then always use request.user and if I want to get to fields I've defined I user `request.user.myobjects.objects.get()` – HenryM Jun 15 '16 at 09:14

0 Answers0