Skip to content

Instantly share code, notes, and snippets.

@jonashaag
Created September 28, 2017 08:57
Show Gist options
  • Select an option

  • Save jonashaag/d4e82f512a2198a78ac9621f1cd56963 to your computer and use it in GitHub Desktop.

Select an option

Save jonashaag/d4e82f512a2198a78ac9621f1cd56963 to your computer and use it in GitHub Desktop.
Django require password confirmation for submit mixin
import django.contrib.auth
import django.core.exceptions
from django import forms
from django.utils.translation import ugettext_lazy as _
class RequiresPasswordMixin(forms.Form):
error_messages = {
'password_incorrect': _("Your old password was entered incorrectly. Please enter it again."),
}
password = forms.CharField(
label=_("Password"),
strip=False,
widget=forms.PasswordInput,
required=True
)
def __init__(self, *args, **kwargs):
self.username = kwargs.pop('username')
super().__init__(*args, **kwargs)
def clean_password(self):
self.user_cache = django.contrib.auth.authenticate(username=self.username, password=self.cleaned_data['password'])
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['password_incorrect'],
code='password_incorrect',
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment