khaganat-web/neluser/forms.py
2019-07-24 19:07:41 +02:00

62 lines
2.2 KiB
Python

from django.contrib.auth.password_validation import validate_password
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from django.contrib import messages
from django import forms
from .models import NelUser
class RegistrationForm(UserCreationForm):
class Meta:
model = NelUser
fields = (NelUser.EMAIL_FIELD,)
class ChangePasswordForm(forms.Form):
current_password = forms.CharField(
label=_("current_password"), widget=forms.PasswordInput
)
new_password = forms.CharField(label=_("new_password"), widget=forms.PasswordInput)
new_password_confirm = forms.CharField(
label=_("new_password_confirm"), widget=forms.PasswordInput
)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
return super().__init__(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
old_pass = cleaned_data.get("current_password")
new_pass = cleaned_data.get("new_password")
new_pass_confirm = cleaned_data.get("new_password_confirm")
user = self.request.user
if new_pass != new_pass_confirm:
msg = _("The new password does not match its confirmation.")
raise forms.ValidationError(msg)
try:
validate_password(new_pass, user=user)
except ValidationError as error:
raise forms.ValidationError(error)
if not user.check_password(old_pass):
msg = _("The current password is incorrect.")
raise forms.ValidationError(msg)
class DeleteAccountForm(forms.Form):
current_password = forms.CharField(
label=_("current_password"), widget=forms.PasswordInput
)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
return super().__init__(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get("current_password")
user = self.request.user
if not user.check_password(password):
msg = _("The current password is incorrect.")
raise forms.ValidationError(msg)