This repository has been archived by the owner on Sep 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
22 Change password
scotwk edited this page May 10, 2015
·
2 revisions
Now that we have a profile page (added in Chapter 21) we can add in new functionality there such as allowing the user to change their password.
from django.views.generic import CreateView, UpdateView, DeleteView, FormView
from django.contrib.auth.forms import SetPasswordForm
from django.contrib.auth import authenticate, login
...
class ProfileView(LoginRequiredMixin, NoteMixin, FormView):
template_name = 'note/profile.html'
form_class = SetPasswordForm
success_url = reverse_lazy('note:index')
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
try:
api_key_obj = ApiKey.objects.get(user=self.request.user)
api_key = api_key_obj.key
except ApiKey.DoesNotExist:
api_key = None
context.update({
'api_key': api_key
})
return context
def get_form_kwargs(self):
""" Our form requires the user. """
kwargs = super(ProfileView, self).get_form_kwargs()
kwargs.update({
'user': self.request.user,
})
return kwargs
def form_valid(self, form):
form.save()
username = self.request.user.username
password = self.request.POST['new_password2']
# If we don't re-authenticate with the new password the user will get logged out.
user = authenticate(username=username, password=password)
login(self.request, user)
return super(ProfileView, self).form_valid(form)
The new profile template: https://github.com/sixfeetup/ElevenNote/raw/22-change-password/elevennote/note/templates/note/profile.html
If the user provides a bad password (such as the fields not matching) the page will report the error to them. But if the user successfully changes their password they do not get an indication, which is not great UX. Can you extend this to add a notification?