def register(request): if request.method == "POST": #Usual test cases if User.objects.filter(username=request.POST['user_reg']).exists(): return render(request, 'user/login.html',{'usr':"******"}) elif User.objects.filter(email=request.POST['email']).exists(): return render(request, 'user/login.html',{'usr':"******"}) elif request.POST['password'] != request.POST['password2']: return render(request, 'user/login.html',{'pwd':" <h4 class='text-danger'>Both the passwords don't match.</h4>"}) else: #Validate the password try: validate_password(request.POST['password']) except ValidationError as e: return render(request, 'user/login.html',{'pwd':password_validators_help_text_html()}) #Yay, new user user = User.objects.create_user(request.POST['user_reg'],request.POST['email'],request.POST['password']) #comm = Communities.objects.get(name='users') profile = UserProfile(user=user) profile.save() user = authenticate(username=request.POST['user_reg'], password=request.POST['password']) auth.login(request, user) return render(request,'user/profile.html') else: return render(request,"user/login.html")
def clean(self): #rewriting clean method to check whether passwords match or not cleaned_data=super(SignupForm,self).clean() username=cleaned_data.get('username') email=cleaned_data.get('email') ps1=cleaned_data.get('password') ps2=cleaned_data.get('verify_password') if email=="": self.add_error('email',"Please input your email!") if ps1!=ps2: msg="Password does not match!" self.add_error('verify_password',msg) # Save hashed password instead of password directly encoded_password=make_password(ps1,make_salt()) cleaned_data['password']=encoded_password # Make sure email is unique if email and User.objects.filter(email=email).exclude(username=username).count(): msg="Email has been used!" self.add_error('email',msg) # Validate password if ps1: try: validate_password(ps1,user=self) cleaned_data['help_text']=None except ValidationError: cleaned_data['help_text']=password_validators_help_text_html() self.add_error('password','Your password it too weak. Please choose another password') return cleaned_data
def test_password_validators_help_text_html_escaping(self): class AmpersandValidator: def get_help_text(self): return 'Must contain &' help_text = password_validators_help_text_html([AmpersandValidator()]) self.assertEqual(help_text, '<ul><li>Must contain &</li></ul>') # help_text is marked safe and therefore unchanged by conditional_escape(). self.assertEqual(help_text, conditional_escape(help_text))
def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) if self.password_required: self.fields['password1'].help_text = ( mark_safe(password_validators_help_text_html()) if django.VERSION >= (1, 9) else '') self.fields['password1'].required = True self.fields['password2'].required = True
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.password_enabled: if self.password_required: self.fields['password1'].help_text = mark_safe(password_validators_help_text_html()) self.fields['password1'].required = True self.fields['password2'].required = True else: del self.fields['password1'] del self.fields['password2']
def __init__(self, *args, **kwargs): kwargs.setdefault('required', True) # Set the min_length attribute if we have a MinimumLenghtValidator for validator in password_validation.get_default_password_validators(): if isinstance(validator, password_validation.MinimumLengthValidator): kwargs.setdefault('min_length', validator.min_length) self.min_length = validator.min_length break kwargs.setdefault('help_text', password_validation.password_validators_help_text_html()) super().__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): instance = kwargs.get('instance') initial = kwargs.get('initial') if instance is not None: if initial is None: initial = {} initial['timezone'] = UserProfile.get_for_user(instance).timezone kwargs['initial'] = initial super().__init__(*args, **kwargs) if self.password_enabled: if self.password_required: self.fields['password1'].help_text = mark_safe(password_validators_help_text_html()) self.fields['password1'].required = True self.fields['password2'].required = True else: del self.fields['password1'] del self.fields['password2']
class PasswordChangeForm(forms.Form): password = forms.CharField( widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html()) password_confirmation = forms.CharField( widget=forms.PasswordInput, help_text='Enter the same password as before, for verification.') def clean_password(self): password = self.cleaned_data.get('password') if password: try: password_validation.validate_password(password) except forms.ValidationError as error: self.add_error('password', error) return password def clean_password_confirmation(self): password = self.cleaned_data.get("password") password_confirmation = self.cleaned_data.get("password_confirmation") if password and password_confirmation and password != password_confirmation: raise forms.ValidationError( 'passwords do not match', code='password_mismatch', ) return password_confirmation def _post_clean(self): ret = super()._post_clean() password = self.cleaned_data.get('password_confirmation') if password: try: password_validation.validate_password(password) except forms.ValidationError as error: self.add_error('password_confirmation', error) return ret
def self_register(request): area_list = Area.objects.all().order_by('name') context = { 'area_list': area_list, 'password_help_text': password_validation.password_validators_help_text_html(), } if request.method == 'POST': areas = request.POST.getlist('areas') context['selected_areas'] = areas form = UserSelfCreationForm(request.POST) context['form'] = form if form.is_valid(): user = form.save(commit=False) user.save() user.areas.set(Area.objects.all().filter(name__in=areas)) user.save() context['register_success'] = True # Send confirmation e-mail current_site = get_current_site(request) html_message = render_to_string( 'registration/email_confirmation.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) send_mail( 'Activate your DJINN account', '', '*****@*****.**', ['*****@*****.**'], # [user.email], html_message=html_message, ) return render(request, 'registration/register.html', context) else: return render(request, 'registration/register.html', context)
class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = ( 'email', 'is_staff', 'is_active', 'name', ) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
class UserChangePwForm(CremeForm): error_messages = { # 'password_mismatch': _("The two password fields didn't match."), 'password_mismatch': auth_forms.SetPasswordForm.error_messages['password_mismatch'], } password_1 = CharField( label=_('Password'), strip=False, widget=PasswordInput(attrs={'autocomplete': 'new-password'}), help_text=password_validation.password_validators_help_text_html(), ) password_2 = CharField( label=_('Password (again)'), strip=False, widget=PasswordInput(attrs={'autocomplete': 'new-password'}), help_text=_('Enter the same password as before, for verification.'), ) def __init__(self, *args, **kwargs): self.user2edit = kwargs.pop('instance') super().__init__(*args, **kwargs) def clean_password_2(self): data = self.data pw2 = data['password_2'] if data['password_1'] != pw2: raise ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) password_validation.validate_password(pw2, self.user2edit) return pw2 def save(self): user = self.user2edit user.set_password(self.cleaned_data.get('password_1')) user.save()
class SetPasswordForm(forms.Form): password = BootstrapPasswordField( widget=BootstrapPasswordInput(glyphicon=True), add_min_length=True, label=_('Password'), help_text=password_validation.password_validators_help_text_html()) password2 = BootstrapPasswordField( widget=BootstrapPasswordInput(glyphicon=True), add_min_length=True, label=_('Confirm'), help_text=_( 'Confirm the password to make sure you spelled it correctly.')) password_error_messages = { 'password_mismatch': _("The two password fields didn't match.") } def __init__(self, *args, **kwargs): self.instance = kwargs.pop('instance', None) super(SetPasswordForm, self).__init__(*args, **kwargs) def clean_password2(self): password2 = self.cleaned_data.get("password2") password_validation.validate_password( self.cleaned_data.get('password2'), self.instance) return password2 def clean(self): cleaned_data = super(SetPasswordForm, self).clean() password1 = cleaned_data.get('password') password2 = cleaned_data.get('password2') if password1 and password2: if password1 != password2: self.add_error( 'password2', self.password_error_messages['password_mismatch']) class Media: js = ('account/js/set_password.js', )
class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label='Адрес электронной почты') password1 = forms.CharField(label='Пароль', widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html() ) password2 = forms.CharField(label='Пароль (повторно)', widget=forms.PasswordInput, help_text='Введите тот же самый пароль еще раз для проверки') def clean_password1(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 and password2 and password1 != password2: errors = {'password2': ValidationError( 'Введенные пароли не совпадают', code='password_mismatch' )} raise ValidationError(errors) def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) user.is_active = False user.is_activated = False if commit: user.save() user_registrated.send(RegisterUserForm, instance=user) return user class Meta: model = AdvUser fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name', 'send_messages')
class SuperRegistrtionForm(UserCreationForm): email = forms.EmailField(required=True, label=_("Email"), widget=forms.EmailInput({ 'class': 'form-control', 'placeholder': 'Email' })) username = forms.CharField(max_length=254, widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'Company name' })) password1 = forms.CharField( label=_("Password"), widget=forms.PasswordInput({ 'class': 'form-control', 'placeholder': 'Password' }), help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label=_("Confirm Password"), widget=forms.PasswordInput({ 'class': 'form-control', 'placeholder': 'Confirm Password' })) class Meta: model = User fields = ('username', 'email', 'password1', 'password2') def save(self, commit=True): user = super(SuperRegistrtionForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.is_superuser = True if commit: user.save() return user
class RegisterUserForm(forms.ModelForm): email = forms.EmailField(label="adress email", required=True) password1 = forms.CharField( label="first password", widget=forms.PasswordInput, #all password requirements help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label="second passwor", widget=forms.PasswordInput, help_text="input password again") def clean_password_first(self): password = self.cleaned_data['password1'] if password: password_validation.validate_password(password) return password def clean(self): super().clean() password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 != password2: error = {'password': ValidationError('password missmatch')} raise ValidationError(error) def save(self, commit=True): #when saving new user user = super().save(commit=False) # dont save in model user.set_password(self.cleaned_data['password1']) #encoding password user.is_active = False #cant log in yet user.is_activated = False if commit: user.save() user_registered_signal.send(RegisterUserForm, instance=user) #sending sign return user #to send user an email requistion activation class Meta: model = AdvUser fields = ('username', 'first_name', 'last_name', 'password1', 'password2', 'email', 'send_message')
class CustomPasswordForm(SetPasswordForm): """ Form para redefinição de senha """ error_messages = { 'password_mismatch': ("As senhas inseridas não são iguais"), } new_password1 = forms.CharField( label=("Nova senha"), widget=forms.PasswordInput, strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=("Confirme nova senha"), widget=forms.PasswordInput, strip=False, ) def __init__(self, user, *args, **kwargs): self.user = user super(SetPasswordForm, self).__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): self.user.set_password(self.cleaned_data['new_password1']) if commit: self.user.save() return self.user
class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change their password by entering their old password. """ error_messages = { **SetPasswordForm.error_messages, 'password_incorrect': _("Your old password was entered incorrectly. Please enter it again."), } old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput(attrs={'class': 'form-control', 'autofocus': True}), ) new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput(attrs={'class': 'form-control'}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={'class': 'form-control'}), ) field_order = ['old_password', 'new_password1', 'new_password2'] def clean_old_password(self): """ Validate that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return old_password
class ActivationForm(PasswordConfirmMixin, forms.Form): """ Form to set password, and optionally user's profile information in an activation view. """ submit_title = 'Activate' error_messages = { 'password_mismatch': _("Password and password confirmation"\ " do not match."), } email = forms.EmailField( widget=forms.TextInput(attrs={'placeholder':'Email', 'maxlength': 75}), label=_("E-mail address"), disabled=True) full_name = forms.RegexField( regex=r'^[\w\s]+$', max_length=60, widget=forms.TextInput(attrs={'placeholder':'Full name'}), label=_("Full name"), error_messages={'invalid': _("Sorry we do not recognize some characters in your full name.")}) username = forms.CharField(widget=forms.TextInput( attrs={'placeholder': _("Username")}), max_length=254, label=_("Username"), error_messages={'invalid': _("Username may only contain letters,"\ " digits and -/_ characters. Spaces are not allowed.")}) new_password = forms.CharField(strip=False, label=_("Password"), widget=forms.PasswordInput(attrs={'placeholder': _("Password")}), help_text=password_validation.password_validators_help_text_html()) new_password2 = forms.CharField(strip=False, label=_("Confirm password"), widget=forms.PasswordInput(attrs={ 'placeholder': _("Confirm password")})) def __init__(self, *args, **kwargs): self.user = kwargs.pop('instance') super(ActivationForm, self).__init__(*args, **kwargs) if settings.REQUIRES_RECAPTCHA: self.fields['captcha'] = ReCaptchaField()
class UserCreationForm(forms.ModelForm): """Validates the user creation process.""" password1 = forms.CharField( strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( widget=forms.PasswordInput, strip=False, help_text=_('Put your password again'), ) class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'is_active', 'is_staff' ] def clean_password2(self): """Validates two passwords and username.""" password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError(_('Passwords Mismatch')) self.instance.username = self.cleaned_data.get('username') password_validation.validate_password( self.cleaned_data.get('password2'), self.instance) return password2 def save(self, commit=True): """Saves the user data.""" user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user
class RegistrationForm(UserCreationForm): password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput( attrs={ 'autocomplete': 'new-password', 'class': 'input_user', 'placeholder': 'Password' }), help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput( attrs={ 'autocomplete': 'new-password', 'class': 'input_user', 'placeholder': 'Confirm password' }), strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2') widgets = { 'username': forms.TextInput(attrs={ 'class': 'input_user', 'placeholder': 'Username' }), 'email': forms.EmailInput(attrs={ 'class': 'input_user', 'placeholder': 'Mail' }), }
class SetPasswordForm(forms.Form): """ A form that lets a user change set their password without entering the old password """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput, strip=False, help_text=password_validation.password_validators_help_text_html()) new_password2 = forms.CharField(label=_("New password confirmation"), strip=False, widget=forms.PasswordInput) def __init__(self, user, *args, **kwargs): self.user = user super(SetPasswordForm, self).__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user
class Meta: model = get_user_model() fields = ('username', 'chinese_name', 'deparment', 'password', 'password1', 'email', 'phone', 'photo', 'addr') widgets = { 'username': forms.TextInput(attrs={'class': 'form-control'}), 'password': forms.PasswordInput(attrs={'class': 'form-control'}), 'chinese_name': forms.TextInput(attrs={ 'class': 'form-control', 'required': '' }), 'deparment': forms.Select(attrs={ 'class': 'form-control', 'required': '' }), 'email': forms.TextInput(attrs={ 'class': 'form-control', 'required': '' }), 'phone': forms.TextInput(attrs={ 'class': 'form-control', 'required': '' }), 'photo': forms.FileInput(attrs={'class': 'custom-file-input'}), 'addr': forms.TextInput(attrs={'class': 'form-control'}), } help_texts = { 'password': password_validation.password_validators_help_text_html(), }
class CustomSetPasswordForm(SetPasswordForm): """Customised set password form for css magic..""" new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput( attrs={ "class": "form-control", "placeholder": "New Password", "autocomplete": "none", }), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput( attrs={ "class": "form-control", "placeholder": "New password confirmation", "autocomplete": "password", }))
class Meta(UserCreationForm): model = CustomUser fields = ('email', 'name') widgets = { 'email': EmailInput(attrs={ 'class': 'form-control', 'required': True, 'placeholder': 'Email' }), 'name': TextInput(attrs={ 'class': 'form-control', 'required': True, 'placeholder': 'Name' }), 'password1': PasswordInput( attrs={ 'class': 'form-control', 'required': True, 'autocomplete': False, 'placeholder': 'Password', 'help_text': password_validation.password_validators_help_text_html() }), 'password2': PasswordInput( attrs={ 'class': 'form-control', 'required': True, 'placeholder': 'Password Confirmation' }), }
class MyPasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) old_password = forms.CharField( label="Old password", strip=False, widget=forms.PasswordInput(attrs={"class": "form-control"}), ) new_password1 = forms.CharField( label="New password", widget=forms.PasswordInput(attrs={"class": "form-control"}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label="New password confirmation", strip=False, widget=forms.PasswordInput(attrs={"class": "form-control"}), )
class UserAdminCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = ("username", ) # field_classes = {'username': UsernameField} def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
class OutsiderPwresetForm(forms.ModelForm): """学外アカウントのパスワード再設定 """ class Meta: model = User fields = ['password'] password = forms.CharField( label="新しいパスワード", strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), help_text=password_validation.password_validators_help_text_html(), ) def clean(self): cleaned_data = super().clean() # パスワード強度チェック try: password_validation.validate_password( cleaned_data.get('password'), self.instance) except ValidationError as error: self.add_error('password', error)
class UserRegisterForm(forms.UserCreationForm): password1 = django_forms.CharField( label=_("Password"), strip=False, widget=django_forms.PasswordInput( attrs={ 'autocomplete': 'new-password', 'onblur': 'SavePassword1(this.value)', 'onkeyup': 'SavePassword1(this.value)', 'onfocus': 'SavePassword1(this.value)' }), help_text=password_validation.password_validators_help_text_html(), ) password2 = django_forms.CharField( label=_("Password confirmation"), widget=django_forms.PasswordInput( attrs={ 'autocomplete': 'new-password', 'onblur': 'SavePassword2(this.value)', 'onkeyup': 'SavePassword2(this.value)', 'onfocus': 'SavePassword2(this.value)' }), strip=False, help_text=_("Enter the same password as before, for verification."), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({ 'autofocus': True, 'onblur': 'SaveUsername(this.value)', 'onkeyup': 'SaveUsername(this.value)', 'onfocus': 'SaveUsername(this.value)' })
class EditUserForm(forms.ModelForm): new_password = forms.CharField( label='Password', widget=forms.PasswordInput, strip=False, help_text=password_validation.password_validators_help_text_html(), ) class Meta: model = UserModel fields = ('email', ) def clean_new_password(self): password = self.cleaned_data.get('new_password') password_validation.validate_password(password, self.instance) return password def save(self, **kwargs): password = self.cleaned_data['new_password'] if password: self.instance.set_password(password) return super().save(**kwargs)
class TSetPasswordForm(SetPasswordForm): new_password1 = forms.CharField( label=_('New password'), widget=forms.PasswordInput( attrs={ 'placeholder': 'New password', 'autocomplete': 'new-password', 'class': FIELD_CLASS }), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_('New password confirmation'), strip=False, widget=forms.PasswordInput( attrs={ 'placeholder': 'New password (again)', 'autocomplete': 'new-password', 'class': FIELD_CLASS }), )
class SetPasswordForm(DjangoSetPasswordForm): new_password1 = PasswordField( label=_("New password"), help_text=password_validation.password_validators_help_text_html(), ) new_password2 = PasswordField( label=_("New password confirmation"), ) # pylint: disable=arguments-differ,signature-differs def save(self, request, delete_session=False): notify_account_activity( self.user, request, 'password', password=self.user.password ) # Change the password password = self.cleaned_data["new_password1"] self.user.set_password(password) self.user.save(update_fields=['password']) if delete_session: request.session.flush() else: # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(request, self.user) # Change key for current session request.session.cycle_key() # Invalidate password reset codes invalidate_reset_codes(self.user) messages.success( request, _('Your password has been changed.') )
class SignUpForm(UserCreationForm): username = UsernameField() first_name = forms.CharField(max_length=150, required=False, help_text='Optional.') last_name = forms.CharField(max_length=150, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required.') password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), strip=False, help_text=_("Enter the same password as before, for verification."), ) username.widget.attrs.update({'class': 'form-control'}) first_name.widget.attrs.update({'class': 'form-control'}) last_name.widget.attrs.update({'class': 'form-control'}) email.widget.attrs.update({'class': 'form-control'}) password1.widget.attrs.update({'class': 'form-control'}) password2.widget.attrs.update({'class': 'form-control'}) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
class PasswordChangeForm(pcf): old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput(attrs={ 'autofocus': True, 'class': 'form-control' }), ) new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput(attrs={'class': 'form-control'}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={'class': 'form-control'}), )
class SignUpForm(UserCreationForm): error_messages = { 'password_mismatch': 'Пароли не совпадают.', } password1 = forms.CharField( label="Пароль", strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label="Подтверждение пароля", widget=forms.PasswordInput, strip=False, help_text="Enter the same password as before, for verification.", ) class Meta: model = PhonebookUser fields = ('username', 'name', 'surname', 'phone', 'email', 'age', 'gender', 'work_status', 'city', 'address', 'password1', 'password2')
class UpdatePasswordForm(PasswordChangeForm): old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput(attrs={ "autofocus": True, "placeholder": "Write current password" }), ) new_password1 = forms.CharField( label=_("New password"), strip=False, help_text=password_validation.password_validators_help_text_html(), widget=forms.PasswordInput( attrs={"placeholder": "Write new password"}), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput( attrs={"placeholder": "Verify new password"}), )
class UserCreationForm(forms.ModelForm): password = forms.CharField( label='Password', strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), help_text=password_validation.password_validators_help_text_html(), ) class Meta: model = User fields = ('email', 'username') def clean_password(self): password = self.cleaned_data.get("password") return password def _post_clean(self): super()._post_clean() email = self.cleaned_data.get('email') if email: try: HPIEmailValidator()(email) except ValidationError as error: self.add_error('email', error) # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password') if password: try: password_validation.validate_password(password, self.instance) except ValidationError as error: self.add_error('password', error) def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user
class NewUserWithPasswordForm(NewUserForm): password = forms.CharField( widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'autocomplete': 'new-password' }), label=_('Password'), help_text=password_validators_help_text_html(), min_length=settings.MIN_PASSWORD_LENGTH, ) password2 = forms.CharField( widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'autocomplete': 'new-password' }), label=_('Password (repeat)')) def clean(self): cleaned = super().clean() if cleaned['password'] != cleaned['password2']: raise forms.ValidationError(_("Passwords do not match!")) return cleaned
def test_empty_password_validator_help_text_html(self): self.assertEqual(password_validators_help_text_html(), '')
def test_password_validators_help_text_html(self): help_text = password_validators_help_text_html() self.assertEqual(help_text.count('<li>'), 2) self.assertIn('12 characters', help_text)
def __init__(self, **kwargs): super(UserCreateForm, self).__init__(**kwargs) self.fields['username'].help_text = None self.fields['password1'].help_text = password_validation.password_validators_help_text_html()