my question is a bit similar to what was asked here: How to implement password change form in Django 1.9
I try to create a profiles page for my users in Django where in addition to changing the password the user can also unsubscribe from the mailings list etc. In addition, after changing the password I want to redirect to the same page and not the changed_password_done template. I am new to Django and want to do things Django conform. My solution works but I want to be as conform as possible. What I did now is creating a class based view like this:
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
class EditProfile(LoginRequiredMixin, View):
template_name = "profile.html"
title = "Edit profile"
def get(self, request, *args, **kwargs):
form = PasswordChangeForm(user=request.user)
return render(request, self.template_name, {'title': self.title,
'form': form})
def post(self, request, *args, **kwargs):
form = PasswordChangeForm(user=request.user, data=request.POST)
context = {
'title': self.title,
'form': form
}
if form.is_valid():
form.save()
# Updating the password logs out all other sessions for the user
# except the current one.
update_session_auth_hash(request, form.user)
context.update({'updated': True})
return render(request, self.template_name, context)
I did not add the other logic like unsubscribe yet but I wanted to know if this is a viable option or if there is a better way to handle the password change request in Django. Should I maybe subclass the form or the password change functionality?
Thanks! Hope it makes sense.
EDIT:
I tried this but the problem is that I can't intercept that the password changed since 'profile' will be reversed to the same URL as the profiles page. Since all POST/GET informations are destroyed there is no way I can know that I was redirected:
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import password_change
from django.contrib.auth.forms import PasswordChangeForm
class EditProfile(LoginRequiredMixin, View):
template_name = "profile.html"
title = "Edit profile"
def get(self, request, *args, **kwargs):
form = PasswordChangeForm(user=request.user)
return render(request, self.template_name, {'title': self.title,
'form': form,
})
def post(self, request, *args, **kwargs):
return password_change(request, self.template_name, 'profile')