123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- from django import forms
- from django.contrib.auth.models import User
- from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm
- from django.utils.translation import gettext as _
- from .models import UserProfile, get_userprofile
- from users import emails
-
-
- class UserRegistrationForm(UserCreationForm):
- email = forms.EmailField()
-
- class Meta:
- model = User
- fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2']
-
-
- class UserProfileForm(forms.ModelForm):
- class Meta:
- model = UserProfile
- fields = ['timezone', 'language_code']
-
-
- class UserProfileFormLanguageOnly(forms.ModelForm):
- class Meta:
- model = UserProfile
- fields = ['language_code']
-
-
- class UserPasswordChangeForm(PasswordChangeForm):
- email = forms.EmailField()
- first_name = forms.CharField(max_length=150)
- last_name = forms.CharField(max_length=150)
- field_order = ["email", "first_name", "last_name", "old_password", "new_password1", "new_password2"]
-
- def __init__(self, request):
- self.request = request
- #
- data = request.POST or {'email': request.user.email, 'first_name': request.user.first_name, 'last_name': request.user.last_name}
- #
- super().__init__(request.user, data)
- self.fields['old_password'].widget.attrs.update({'autofocus': False})
- self.fields['old_password'].required = False
-
- def clean_old_password(self):
- """
- Validation of old_password field only, if set.
- """
- old_password = self.cleaned_data["old_password"]
- if old_password and not self.user.check_password(old_password):
- raise forms.ValidationError(
- self.error_messages["password_incorrect"],
- code="password_incorrect",
- )
- return old_password
-
- def clean(self):
- """
- Validation of new_passwords only if old_password field is set.
- """
- clean_data = forms.Form.clean(self)
- old_password = clean_data.get('old_password')
- #
- if old_password:
- self.validate_passwords("new_password1", "new_password2")
- self.validate_password_for_user(self.user, "new_password2")
- return forms.Form.clean(self)
-
- def save(self, commit=True):
- changed = False
- for key in self.fields:
- new = self.data.get(key)
- try:
- old = getattr(self.user, key)
- except AttributeError:
- pass # Is a password field
- else:
- if new != old:
- if key == 'email':
- emails.send_validation_mail(self.user, self.request)
- up = get_userprofile(self.user)
- up.mail_pending = new
- up.save()
- else:
- changed = True
- setattr(self.user, key, new)
- if self.data.get('new_password1'):
- changed = True
- self.user.set_password(self.data.get('new_password1'))
- #
- if changed:
- self.user.save()
- return changed
-
-
- class UserActivationForm(UserChangeForm):
- password = None
-
- class Meta:
- model = User
- fields = ['is_active', 'is_staff']
|