class UserForm(forms.ModelForm): new_password = forms.CharField(widget=forms.PasswordInput(), required=False) new_password_confirm = forms.CharField(widget=forms.PasswordInput(), required=False) class Meta: model = User fields = [ 'username', 'email', ] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(UserForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(UserForm, self).clean() new_password = cleaned_data.get('new_password') new_password_confirm = cleaned_data.get('new_password_confirm') if new_password != new_password_confirm: raise ValidationError('Password fields did not match.') def save(self, commit=True): if self.cleaned_data['new_password']: self.user.set_password(self.cleaned_data['new_password']) return super(UserForm, self).save(commit=commit)
class UserDeleteForm(forms.Form): CONFIRMATION_PHRASE = str(_('Freedom of Information Act')) password = forms.CharField( widget=forms.PasswordInput(), label=_('Password'), help_text=_('Please type your password to confirm.')) confirmation = forms.CharField( widget=ConfirmationWidget({'placeholder': CONFIRMATION_PHRASE}), label=_('Confirmation Phrase'), help_text=_('Type the phrase above exactly as displayed.')) def __init__(self, user, *args, **kwargs): self.user = user super(UserDeleteForm, self).__init__(*args, **kwargs) def clean_password(self): password = self.cleaned_data['password'] user = auth.authenticate(username=self.user.email, password=password) if not user: raise forms.ValidationError(_('You provided the wrong password!')) return '' def clean_confirmation(self): confirmation = self.cleaned_data['confirmation'] if confirmation != self.CONFIRMATION_PHRASE: raise forms.ValidationError( _('You did not type the confirmation phrase exactly right!')) return ''
def test_change_widget(self): form = SimpleForm() config = FormConfig() config.configure('widget', forms.PasswordInput(), filter=ConfigFilter(form['name'])) self.assertHTMLEqual(render("""{% form myform using %} {% formfield form.name %} {% endform %}""", {'myform': form}, config), """<input type="password" name="name" id="id_name" />""")
class UserLoginForm(forms.Form): email = forms.EmailField( widget=forms.EmailInput(attrs={ 'placeholder': _('*****@*****.**'), 'class': 'form-control' }), label=_('Email address')) password = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control'}), label=_('Password'))
class WocatAuthenticationForm(forms.Form, AuthenticationForm): """ Use floppyforms """ username = forms.CharField(max_length=255, label=_(u"E-mail address"), widget=forms.TextInput(attrs={ 'tabindex': 1, 'autofocus': True })) password = forms.CharField( label=_("Password"), widget=forms.PasswordInput(attrs={'tabindex': 2}))
class RegistrationBasicForm(forms.Form): """ First step of the Registration form, requiring User's basic info """ user_name = forms.CharField(max_length=50) email = forms.EmailField(max_length=100) first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) password = forms.CharField(max_length=30, widget=forms.PasswordInput()) confirm_password = forms.CharField(max_length=30, widget=forms.PasswordInput()) def clean_email(self): email = self.cleaned_data['email'] if email: if User.objects.filter(Q(email=email)): raise forms.ValidationError( u'This email address is already registered.') return email def clean_user_name(self): username = self.cleaned_data['user_name'] if username: if User.objects.filter(Q(username=username)): raise forms.ValidationError(u'This username is already taken.') return username def clean(self): cleaned_data = self.cleaned_data password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password and password != confirm_password: msg = u'Passwords do not match. Please try again.' self._errors['confirm_password'] = self.error_class([msg]) return cleaned_data
class SignUpForm(forms.Form): username = forms.CharField(error_messages=RU_ERRORS, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': u'Логин', 'autofocus': ''})) password = forms.CharField(error_messages=RU_ERRORS, widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': u'Пароль'})) password_repeat = forms.CharField(error_messages=RU_ERRORS, widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': u'Повторите пароль'})) def clean(self): cleaned_data = super(SignUpForm, self).clean() password = cleaned_data.get('password') password_repeat = cleaned_data.get('password_repeat') if password != password_repeat: raise forms.ValidationError(u'Пароли не совпадают') return cleaned_data def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).count() != 0: raise forms.ValidationError(u'Пользователь с таким логином уже существует') return self.cleaned_data
class RegistrationForm(forms.Form): #this has to be under a different name due to the fact that register form popup may #appear after user login modal, and if that happens, 'div_id_fieldname' would only pick up the #username field from login pop so login.js applyFormFieldError wouldn't work for username username_register = forms.CharField(max_length=50, label=u'Username') email = forms.EmailField(max_length=100) password = forms.CharField(max_length=30, widget=forms.PasswordInput()) confirm_password = forms.CharField(max_length=30, widget=forms.PasswordInput()) def clean_email(self): email = self.cleaned_data['email'] if email: if User.objects.filter(Q(email=email)): raise forms.ValidationError( u'This email address is already registered.') return email def clean_username_register(self): username = self.cleaned_data['username_register'] if username: if User.objects.filter(Q(username=username)): raise forms.ValidationError(u'This username is already taken.') return username def clean(self): password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') if password and password != confirm_password: msg = u'Passwords do not match. Please try again.' self._errors['confirm_password'] = self.error_class([msg]) return self.cleaned_data
class SignInForm(forms.Form): username = forms.CharField(error_messages=RU_ERRORS, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': u'Логин', 'autofocus': ''})) password = forms.CharField(error_messages=RU_ERRORS, widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': u'Пароль'})) def clean(self): cleaned_data = super(SignInForm, self).clean() if not self.errors: user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password')) if user is None: raise forms.ValidationError(u'Пользователя с таким логином или паролем не существует') self.user = user return cleaned_data def get_user(self): return self.user or None
class LoginForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(max_length=30, widget=forms.PasswordInput()) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') self.user = None if username and password: self.user = authenticate(username=username, password=password) if self.user is None: raise forms.ValidationError( _(u'The username and/or password is incorrect, please try again.' )) elif not self.user.is_active: raise forms.ValidationError(_(u'This user is inactive.')) return self.cleaned_data def get_user(self): return self.user
class PwForm(forms.Form): text = forms.CharField() pw = forms.CharField(widget=forms.PasswordInput(render_value=True))
def __init__(self, *args, **kwargs): super(AuthenticationForm, self).__init__(*args, **kwargs) self.fields['username'].widget = forms.TextInput() self.fields['password'].widget = forms.PasswordInput()
class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password'] widgets = {'password': forms.PasswordInput()}
class SigninForm(forms.Form): email = forms.EmailField(max_length=255) password = forms.CharField(max_length=100, widget=forms.PasswordInput())
class RegistrationForm(forms.Form): """ Form for registering a new user account. Validates that the email address is not already in use, and requires the password to be entered twice to catch typos. Also allows user to either pick from an existing list of schools or enter a new one. """ name = pyoforms.StripCharField(max_length=200) role = pyoforms.StripCharField(max_length=200) password = forms.CharField(widget=forms.PasswordInput(render_value=False)) password_confirm = forms.CharField( label="confirm password", widget=forms.PasswordInput(render_value=False)) email = forms.EmailField(max_length=255) phone = pyoforms.StripCharField(max_length=20) country_code = forms.TypedChoiceField( choices=model.Profile._meta.get_field('country_code').choices, widget=forms.RadioSelect(), ) school = pyoforms.ModelChoiceField( queryset=model.School.objects.filter(auto=False).order_by('name'), empty_label=u"I'm not affiliated with a school or program", required=False, widget=SchoolRadioSelect, initial=u'', ) addschool = forms.BooleanField( initial=False, required=False, widget=forms.HiddenInput) terms_confirm = forms.BooleanField(required=True) def __init__(self, *args, **kwargs): """Also instantiate a nested SchoolForm.""" super(RegistrationForm, self).__init__(*args, **kwargs) self.addschool_form = SchoolForm(self.data or None, prefix='addschool') def clean(self): """ Verify password fields match and school is provided. If addschool is True, build a new School based on data in nested SchoolForm. If not, and no school was selected, auto-construct one. """ data = self.cleaned_data password = data.get('password') confirm = data.get('password_confirm') if password != confirm: raise forms.ValidationError("The passwords didn't match.") if data.get('addschool'): if self.addschool_form.is_valid(): data['school'] = self.addschool_form.save(commit=False) else: raise forms.ValidationError( "Could not add a school.") else: # reinstantiate unbound addschool_form to avoid spurious errors self.addschool_form = SchoolForm(prefix='addschool') if data.get('email') and not data.get('school'): data['school'] = model.School( name=(u"%f-%s" % (time.time(), data['email']))[:200], postcode="", auto=True, ) return data def clean_email(self): """Validate that the supplied email address is unique.""" if model.User.objects.filter( email__iexact=self.cleaned_data['email']): raise forms.ValidationError( "This email address is already in use. " "Please supply a different email address." ) return self.cleaned_data['email'] def save(self): """Save and return new user profile.""" school = self.cleaned_data['school'] if school.id is None: # this could just set country_code and then school.save(), but that # creates a race condition for two users creating same school at # same time, resulting in IntegrityError school, created = model.School.objects.get_or_create( name=school.name, postcode=school.postcode, defaults={ 'country_code': self.cleaned_data['country_code'], 'auto': school.auto, }, ) profile = model.Profile.create_with_user( name=self.cleaned_data['name'], email=self.cleaned_data['email'], password=self.cleaned_data['password'], role=self.cleaned_data['role'], country_code=self.cleaned_data['country_code'], school=school, school_staff=True, email_confirmed=False, is_active=True, email_notifications=True, ) return profile