Пример #1
0
class EmailUsernameRegistrationForm(RegistrationFormUniqueEmail):
    """Registration form that uses the user's email address for the username"""

    # If django-passwords is installed, replace the password fields with
    # the fields from this package for extra validation
    try:
        from passwords.fields import PasswordField
        password1 = PasswordField(label=_("Password"))
        password2 = PasswordField(label=_("Password (again)"))
    except ImportError:
        pass

    required_css_class = 'required'

    def __init__(self, *args, **kwargs):
        super(EmailUsernameRegistrationForm, self).__init__(*args, **kwargs)
        # Remove the username field
        del self.fields['username']

    def clean_email(self):
        """
        Validates email address is unique and sets username field to email 
        """
        email = super(EmailUsernameRegistrationForm, self).clean_email()
        self.cleaned_data['username'] = email
        return email
class StrengthCheckPasswordChangeForm(PasswordChangeForm):
    """
    Use the django-passwords PasswordField
    """

    new_password1 = PasswordField(label=_("New password"))
    new_password2 = PasswordField(label=_("New password confirmation"))
Пример #3
0
class ProfileForm(forms.ModelForm):
    """Form to update User profile."""

    oldpassword = forms.CharField(
        label=ugettext_lazy("Old password"),
        required=False,
        widget=forms.PasswordInput(attrs={"class": "form-control"}))
    newpassword = PasswordField(
        label=ugettext_lazy("New password"),
        required=False,
        widget=forms.PasswordInput(attrs={"class": "form-control"}))
    confirmation = PasswordField(
        label=ugettext_lazy("Confirmation"),
        required=False,
        widget=forms.PasswordInput(attrs={"class": "form-control"}))

    class Meta(object):
        model = User
        fields = ("first_name", "last_name", "language", "phone_number",
                  "secondary_email")
        widgets = {
            "first_name": forms.TextInput(attrs={"class": "form-control"}),
            "last_name": forms.TextInput(attrs={"class": "form-control"})
        }

    def __init__(self, update_password, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        if not update_password:
            del self.fields["oldpassword"]
            del self.fields["newpassword"]
            del self.fields["confirmation"]

    def clean_oldpassword(self):
        if self.cleaned_data["oldpassword"] == "":
            return self.cleaned_data["oldpassword"]

        if param_tools.get_global_parameter("authentication_type") != "local":
            return self.cleaned_data["oldpassword"]

        if not self.instance.check_password(self.cleaned_data["oldpassword"]):
            raise forms.ValidationError(_("Old password mismatchs"))
        return self.cleaned_data["oldpassword"]

    def clean_confirmation(self):
        newpassword = self.cleaned_data["newpassword"]
        confirmation = self.cleaned_data["confirmation"]
        if newpassword != confirmation:
            raise forms.ValidationError(_("Passwords mismatch"))
        return self.cleaned_data["confirmation"]

    def save(self, commit=True):
        user = super(ProfileForm, self).save(commit=False)
        if commit:
            if self.cleaned_data.get("confirmation", "") != "":
                user.set_password(self.cleaned_data["confirmation"],
                                  self.cleaned_data["oldpassword"])
            user.save()
        return user
Пример #4
0
class RegisterForm(forms.Form):

    forms.Form.error_css_class = 'error'

    user_name = forms.CharField(
        help_text='请输入用户名(必填)',
        error_messages={'required': '请填写名字'},
        min_length=4,
        max_length=16,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入用户名(必填)'})
    )

    user_passwd = PasswordField(
        help_text='请输入密码(必填)',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码(必填)'})
    )

    user_passwd_confirm = PasswordField(
        help_text='请再次输入密码(必填)',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请再次输入密码(必填)'})
        # widget=forms.PasswordInput,
    )
    user_email = forms.EmailField(
        help_text='请输入邮箱(选填)',
        required=False,
        widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': '请输入邮箱'})
    )
    auto_login = forms.BooleanField(
        label='自动登录',
        widget=forms.CheckboxInput(attrs={'checked': "checked", 'placeholder': '自动登录'}),       required=False
    )

    def clean(self):
        cleaned_data = super(RegisterForm, self).clean()
        user_name = cleaned_data.get('user_name')
        user_passwd = cleaned_data.get('user_passwd')
        user_passwd_confirm = cleaned_data.get('user_passwd_confirm')
        if User.objects.filter(username=user_name).count():
            # raise forms.ValidationError('用户名已存在,请换其他用户名!')
            msg = '用户名已存在,请换其他用户名!'
            self.add_error('user_name', msg)
        if user_passwd and user_passwd_confirm and user_passwd != user_passwd_confirm:
            msg = '两次输入密码不一致,请重新输入!'
            self.add_error('user_passwd', msg)
        return cleaned_data

    def clean_password(self):
        cleaned_data = super(RegisterForm, self).clean()
        user_passwd = cleaned_data.get('user_passwd')
        user_passwd_confirm = cleaned_data.get('user_passwd_confirm')
        if user_passwd and user_passwd_confirm and user_passwd != user_passwd_confirm:
            raise forms.ValidationError('两次输入密码不一致,请重新输入!')
        return cleaned_data

    class Meta:
        model = User
class UserCreationForm(forms.ModelForm):
    username = forms.CharField(validators=[
        RegexValidator(r'[a-zA-Z0-9]+',
                       _('Username can only contain letters and numbers.'))
    ])
    error_messages = {
        'password_mismatch': _("The two passwords didn't match."),
    }
    password1 = PasswordField(label='Password', widget=forms.PasswordInput)
    password2 = PasswordField(
        label='Password confirmation',
        widget=forms.PasswordInput,
        help_text=_('Enter the same password as above, for verification.'))

    class Meta:
        model = User
        fields = (
            'email',
            'username',
        )

    # def clean_username(self):
    #     data = self.cleaned_data['username']
    #     # if RegexValidator(r'^\S+$'):
    #     #     raise ValidationError(_('Username can not contain spaces.'))
    #     if RegexValidator(r'[^a-zA-Z0-9]+'):
    #         raise ValidationError(_('Username can only contain letters and numbers.'))
    #     return data

    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 _post_clean(self):
        super()._post_clean()
        # Validate the password after self.instance is updated with form data
        # by super().
        password = self.cleaned_data.get('password2')
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except forms.ValidationError as error:
                self.add_error('password2', error)

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user
Пример #6
0
class AccountProfileForm(UserProfileForm):
    new_password = PasswordField(required=False,
                                 help_text=PASSWORD_HELP_TEXT,
                                 label="new password")
    new_password_confirm = PasswordField(required=False,
                                         help_text=PASSWORD_CONFIRM_HELP_TEXT,
                                         label="new password confirmation")
    old_password = PasswordField(required=False,
                                 help_text=OLD_PASSWORD_HELP_TEXT,
                                 label="current password")
Пример #7
0
class StrongSetPasswordForm(SetPasswordForm):
    """A version of SetPasswordForm that uses fields from django-passwords if available"""
    # If django-passwords is installed, replace the password fields with
    # the fields from this package for extra validation
    try:
        from passwords.fields import PasswordField
        new_password1 = PasswordField(label=_("New password"))
        new_password2 = PasswordField(label=_("New password confirmation"))
    except ImportError:
        pass
Пример #8
0
class ProfileForm(forms.ModelForm):
    oldpassword = forms.CharField(
        label=ugettext_lazy("Old password"),
        required=False,
        widget=forms.PasswordInput(attrs={"class": "form-control"}))
    newpassword = PasswordField(
        label=ugettext_lazy("New password"),
        required=False,
        widget=forms.PasswordInput(attrs={"class": "form-control"}))
    confirmation = PasswordField(
        label=ugettext_lazy("Confirmation"),
        required=False,
        widget=forms.PasswordInput(attrs={"class": "form-control"}))

    class Meta:
        model = User
        fields = ("first_name", "last_name")
        widgets = {
            'first_name': forms.TextInput(attrs={'class': 'form-control'}),
            'last_name': forms.TextInput(attrs={'class': 'form-control'})
        }

    def __init__(self, update_password, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        if not update_password:
            del self.fields["oldpassword"]
            del self.fields["newpassword"]
            del self.fields["confirmation"]

    def clean_oldpassword(self):
        if self.cleaned_data["oldpassword"] == "":
            return self.cleaned_data["oldpassword"]

        if parameters.get_admin("AUTHENTICATION_TYPE") != "local":
            return self.cleaned_data["oldpassword"]

        if not self.instance.check_password(self.cleaned_data["oldpassword"]):
            raise forms.ValidationError(_("Old password mismatchs"))
        return self.cleaned_data["oldpassword"]

    def clean_confirmation(self):
        newpassword = self.cleaned_data["newpassword"]
        confirmation = self.cleaned_data["confirmation"]
        if newpassword != confirmation:
            raise forms.ValidationError(_("Passwords mismatch"))
        return self.cleaned_data["confirmation"]

    def save(self, commit=True):
        user = super(ProfileForm, self).save(commit=False)
        if commit:
            if self.cleaned_data.get("confirmation", "") != "":
                user.set_password(self.cleaned_data["confirmation"],
                                  self.cleaned_data["oldpassword"])
            user.save()
        return user
Пример #9
0
class ResetPasswordForm(forms.Form):
    """Reset Password Form."""

    password = PasswordField(label=_("Password"),
                             widget=forms.PasswordInput(
                                 attrs={
                                     "min_length": 6,
                                     "max_length": 30,
                                     "class": "form-control",
                                     "placeholder": _("Password"),
                                     "value": "",
                                 }))
    retry = forms.CharField(widget=forms.PasswordInput(
        attrs={
            "min_length": 6,
            "max_length": 30,
            "class": "form-control",
            "placeholder": _("Retry"),
            "value": "",
        }))

    def clean_retry(self):
        """Docstring."""
        if self.cleaned_data["retry"] != self.cleaned_data.get("password", ""):
            raise forms.ValidationError(_("Passwords don't match."))

        return self.cleaned_data["retry"]
Пример #10
0
class SignupForm(UserCreationForm):
    email = forms.EmailField(required=True, label='Email')
    group = forms.ChoiceField(
        required=True,
        choices=[(index, group.name)
                 for index, group in enumerate(Group.objects.filter())],
        widget=forms.Select(attrs={'class': 'form-control'}))
    password2 = PasswordField(
        label="Password confirmation",
        help_text="Enter the same password as above, for verification.")

    class Meta:
        model = User
        fields = ("username", "email", "group")

    def save(self, commit=True):
        user = super(SignupForm, self).save(commit=False)
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        user_group = self.cleaned_data['group']
        group = Group.objects.get(name=Group.objects.filter()[int(user_group)])

        user.groups.add(group)
        group.user_set.add(user)

        return user
Пример #11
0
class BaseSignupForm(forms.ModelForm):
    """
    Homebuyers/Realtors will use subclasses of this form to sign up.  The view
    that uses this form will then create their User/Homebuyer/Realtor
    instances.
    """
    password = PasswordField(label="Password")
    password_confirmation = forms.CharField(label="Password Confirmation",
                                            widget=forms.PasswordInput)

    class Meta:
        fields = ()
        model = User
        widgets = {
            'password': forms.PasswordInput,
        }

    def clean(self):
        """
        Ensure password matches password_confirmation.
        """
        cleaned_data = super(BaseSignupForm, self).clean()
        password = cleaned_data.get('password')
        password_confirmation = cleaned_data.get('password_confirmation')
        if (password and password_confirmation and
                password != password_confirmation):
            self.add_error('password_confirmation',
                           ValidationError("Passwords do not match."))
        if 'password' in self.errors:
            self.errors['password'] = [settings.PASSWORD_ERROR_MESSAGE]
        return cleaned_data
Пример #12
0
class UserForm(forms.ModelForm):
    username = forms.CharField(min_length=5, max_length=30, required=True)
    password = PasswordField(widget=forms.PasswordInput(),
                             label='Password',
                             required=True)

    password2 = forms.CharField(widget=forms.PasswordInput(),
                                label='Password Confirmation',
                                required=True)

    first_name = forms.CharField(max_length=20, required=True)
    last_name = forms.CharField(max_length=20, required=True)

    def clean_password2(self):
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')

        if not password2:
            raise forms.ValidationError("You must confirm your password")
        if password != password2:
            raise forms.ValidationError("Your passwords do not match")
        return password2

    class Meta:
        model = User
        fields = (
            'username',
            'email',
            'password',
            'password2',
            'first_name',
            'last_name',
        )
Пример #13
0
class SignupForm(account.forms.SignupForm):
    advisor = forms.CharField(label=_("Advisor username (optional)"), required=False)
    first_name = forms.CharField(label=_("First name"))
    last_name = forms.CharField(label=_("Last name"))
    confirm_email = forms.EmailField(label=_("Confirm e-mail"))
    password = PasswordField(label=_("Password"), strip=settings.ACCOUNT_PASSWORD_STRIP)
    terms = forms.BooleanField(label=_("I have read and agree to the terms of use: <a href=\"https://www.xfactor.cash/terms.html\" target=\"blank\">open terms</a>"))
    
    field_order = ['type', 'advisor', 'first_name', 'last_name', 'username', 'email', 'confirm_email', 'password', 'password_confirm', 'term']

    # Valida o campo de confirmar e-mail
    def clean_confirm_email(self):
        email = self.cleaned_data.get('email')
        confirm_email = self.cleaned_data.get('confirm_email')

        if not email == confirm_email:
            raise forms.ValidationError(_("The e-mails aren't equal"))

        return confirm_email

    def clean_advisor(self):
        advisor = self.cleaned_data['advisor']

        if len(advisor) > 0:
            if not Users.objects.filter(username=advisor, is_active=True, graduations__type=Graduations._advisor).exists():
                raise forms.ValidationError(_("Advisor doesn't exists"))

        return
Пример #14
0
class SignupUserFrom(forms.ModelForm):

    password = PasswordField()
    repassword = forms.CharField(widget=forms.PasswordInput(),
                                 label=_('Password (again)'))

    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'password',
        ]

        labels = {
            'username': _('User name'),
        }

    def clean(self):
        if 'password' in self.cleaned_data and 'repassword' in self.cleaned_data:
            if self.cleaned_data["password"] != self.cleaned_data["repassword"]:
                self.add_error(
                    'repassword',
                    forms.ValidationError(
                        _("You must type the same password each time,"),
                        code='error_password'))
Пример #15
0
class ChangePasswordForm(Form):
    password = CharField(
        label="Password",
        widget=PasswordInput(attrs={'placeholder': 'Password'}))
    new_password1 = PasswordField(
        label=('New Password'),
        widget=PasswordInput(attrs={
            'placeholder': 'New Password',
            # so broken :-(
            'class': 'broken'
        }),
        help_text="Must contain an uppercase "
        "letter, lowercase letter, number, "
        "and special character.")
    new_password2 = CharField(
        label="New Password (again)",
        widget=PasswordInput(attrs={'placeholder': 'New Password (again)'}))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(ChangePasswordForm, self).__init__(*args, **kwargs)

    def clean_new_password1(self):
        new_password = self.cleaned_data['new_password1']
        if self.user.is_password_in_history(new_password):
            limit = settings.PASSWORD_HISTORY_ENTRIES
            raise ValidationError(
                u'The new password must be different from the ' +
                u'previous %(count)d passwords',
                params={'count': limit})
        else:
            return self.cleaned_data['new_password1']

    def clean_password(self):
        password = self.cleaned_data['password']
        if not self.user.check_password(password):
            raise ValidationError(("Wrong password."))
        else:
            return self.cleaned_data['password']

    def clean(self):
        cleaned_data = super(ChangePasswordForm, self).clean()
        if 'new_password1' in self.cleaned_data and 'new_password2' in self.cleaned_data:
            if self.cleaned_data['new_password1'] != self.cleaned_data[
                    'new_password2']:
                error_msg = u"The new password fields did not match."
                self._errors["new_password1"] = self.error_class([error_msg])
                self._errors["new_password2"] = self.error_class([error_msg])

                # These fields are no longer valid. Remove them from the
                # cleaned data.
                del cleaned_data["new_password1"]
                del cleaned_data["new_password2"]
            else:
                return self.cleaned_data

    def save(self):
        self.user.set_password(self.cleaned_data["new_password1"])
        self.user.save()
Пример #16
0
class PasswordChangeForm(PasswordChangeForm):
    new_password1 = PasswordField(label="New password")

    def clean(self):
        cleaned_data = super(PasswordChangeForm, self).clean()
        if 'new_password1' in self.errors:
            self.errors['new_password1'] = [settings.PASSWORD_ERROR_MESSAGE]
        return cleaned_data
Пример #17
0
class SetStrongPasswordForm(SetPasswordForm):
    """
    The Django SetPasswordForm with django-passwords PasswordField
    """
    new_password2 = PasswordField(
        label=_("New password confirmation"),
        widget=forms.PasswordInput
    )
Пример #18
0
class LoginForm(forms.Form):
    username = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control'}),
                                label='')
    password = PasswordField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control'}),
                             label='')

    class Meta:
        fields = ['username', 'password']
Пример #19
0
class RegistrationForm(forms.Form):
    first_name = forms.CharField(label='first name', max_length=30)
    #middle_name = forms.CharField(label='middle name', max_length=30, required=False)
    last_name = forms.CharField(label='last name', max_length=30)
    #username = forms.CharField(label='username', max_length=15)
    email = forms.EmailField()
    password = PasswordField(label='password')
    re_password = PasswordField(label='re-enter password')
    #password = forms.CharField(label='password', max_length=16, min_length=8, widget=forms.PasswordInput)
    #re_password = forms.CharField(label='re-enter password', max_length=16, min_length=8, widget=forms.PasswordInput)
    #dob = forms.DateField(label='date_of_birth',  input_formats=['%d/%m/%Y'])
    #country = forms.CharField(label='country', max_length=20)
    terms = forms.BooleanField(error_messages={
        'required':
        'You must accept the terms and conditions'
    },
                               label="Terms&Conditions")
Пример #20
0
class RegistrationForm(forms.Form):
    email = forms.EmailField(error_messages={'required': 'Email is required.'},
                             label=_("Email"), required=True,
                             widget=forms.TextInput(attrs={
                                 'id': 'id_email',
                                 'autocomplete': 'off'}),
                             max_length=255)
    password1 = PasswordField(error_messages={'required':
                                              'Password is required.'},
                              label=('Password'), required=True,
                              widget=forms.PasswordInput(attrs={
                                  'id': 'id_password1',
                                  'autocomplete': 'off'}),
                              help_text="Must contain an uppercase "
                                        "letter, lowercase letter, digit, and "
                                        "special character.")
    password2 = forms.CharField(error_messages={'required':
                                                'Password is required.'},
                                label=_("Password (again)"), required=True,
                                widget=forms.PasswordInput(attrs={
                                    'id': 'id_password2',
                                    'autocomplete': 'off'},
                                    render_value=False))

    def clean(self):
        """
        Validate that the username is not already in use and that
        the values entered into the two password fields match.
        """

        if 'email' in self.cleaned_data and User.objects.get_email_owner(
                self.cleaned_data['email']):
            raise forms.ValidationError(
                _("A user with that email already exists."))

        if 'password1' in self._errors:
            self._errors['password1'] = [
                error if error.endswith('.') else 'Password Error: ' + error
                for error in self._errors['password1'][:]]

        if 'password2' in self._errors:
            self._errors['password1'] = [
                error if error.endswith('.') else 'Password Error: ' + error
                for error in self._errors['password2'][:]]

        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                error_msg = u"The new password fields did not match."
                self._errors["password1"] = self.error_class([error_msg])
                # needed to ensure field is wrapped by error class
                self._errors["password2"] = self.error_class([""])

                # These fields are no longer valid. Remove them from the
                # cleaned data.
                del self.cleaned_data["password1"]
                del self.cleaned_data["password2"]

        return self.cleaned_data
Пример #21
0
class ServiceUserForm(forms.ModelForm):
    password = PasswordField(label="Password")

    def clean_password(self):
        password = self.cleaned_data['password']
        return ServiceUser.get_encrypted(password)

    class Meta:
        exclude = []
        model = ServiceUser
class ChangePasswordForm(PasswordVerificationMixin, UserForm):

    oldpassword = PasswordField(label=_('Current Password'))
    password1 = PasswordField(label=_('New Password'))
    password2 = PasswordField(label=_('Confirm New Password'))

    def __init__(self, *args, **kwargs):
        super(ChangePasswordForm, self).__init__(*args, **kwargs)
        self.fields['password1'].user = self.user

    def clean_oldpassword(self):
        if not self.user.check_password(self.cleaned_data.get('oldpassword')):
            raise forms.ValidationError(
                _('Please type your current'
                  ' password.'))
        return self.cleaned_data['oldpassword']

    def save(self):
        get_adapter().set_password(self.user, self.cleaned_data['password1'])
Пример #23
0
class registration(forms.ModelForm):
    username = forms.CharField()
    password = PasswordField(validators=[
        ComplexityValidator(complexities=dict(DIGITS=1)),
    ])
    password1 = PasswordField(validators=[
        ComplexityValidator(complexities=dict(DIGITS=1)),
    ])

    # field = forms.CharField(validators=[
    #     DictionaryValidator(words=['anal','kuma','mkundu'], threshold=0.9),
    # ])

    class Meta:
        model = User
        fields = ['username', 'password', 'password1']

    def clean(self):
        cleaned_data = super(registration, self).clean()
        if 'password' in self.cleaned_data and 'password1' in self.cleaned_data:
            if self.cleaned_data['password'] != self.cleaned_data['password1']:
                self._errors['password'] = '******'
                self._errors['password1'] = 'Password Must Match'
        if 'username' in self.cleaned_data and 'username1' in self.cleaned_data:
            if self.cleaned_data['username'] != self.cleaned_data['username1']:
                self._errors['username'] = '******'
                self._errors['username1'] = 'Phone Number Must Match'
        if 'username' in self.cleaned_data:
            if self.cleaned_data['username'] and User.objects.filter(
                    username=self.cleaned_data['username']).count() > 0:
                self._errors[
                    'username'] = '******'
        return self.cleaned_data

    def save(self, commit=True):
        user = super(registration, self).save(commit=False)
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.last_login = timezone.now()
            user.is_active = False
            user.save()
        return user
Пример #24
0
class Reset_Password_Form(forms.Form):
    password = PasswordField(label="Password")
    confirm_password = forms.CharField(widget=forms.PasswordInput)
    user_email = forms.CharField(widget=forms.HiddenInput())
    activation_code = forms.CharField(widget=forms.HiddenInput())

    def clean(self):
        cleaned_data = super(Reset_Password_Form, self).clean()
        if 'password' in self.cleaned_data and 'confirm_password' in self.cleaned_data:
            if self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
                raise forms.ValidationError("Passwords don't match. Please enter both fields again.")
        return self.cleaned_data
Пример #25
0
class UserForm(forms.ModelForm):
    password = PasswordField(label="Password", widget=forms.PasswordInput())
    terms = forms.BooleanField(
        required=True,
        error_messages={
            'required': 'You must accept the terms and conditions'
        },
        label="I have read and agree to the terms and conditions")

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password')
class SetPasswordFormTOS(SetPasswordForm):
    """
    Subclass of ``SetPasswordForm`` which adds a required checkbox
    for agreeing to a site's Terms of Service.

    """
    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
    }
    new_password1 = PasswordField(label=_("New password"))
    new_password1 = PasswordField(label=_("New password confirmation"))
    tos = forms.BooleanField(widget=forms.CheckboxInput(),
                             label=_('I have read and agree to the Terms of Service'),
                             required=True)

    def clean_tos(self):
        """
        Validate that the user accepted the Terms of Service.

        """
        if self.cleaned_data.get('tos', False):
            return self.cleaned_data['tos']
        raise forms.ValidationError(_('You must agree to the terms to register'))
Пример #27
0
class UserSignup(forms.ModelForm):
    password1 = PasswordField(widget=forms.PasswordInput(
        attrs={'placeholder': 'Password'}))
    password2 = PasswordField(widget=forms.PasswordInput(
        attrs={'placeholder': 'Confirm Password'}))

    class Meta:
        model = get_user_model()
        fields = [
            'email', 'first_name', 'last_name', 'phone_number', 'user_type'
        ]
        widgets = {
            'email': forms.TextInput(attrs={'placeholder': 'Email'}),
            'first_name': forms.TextInput(attrs={'placeholder': 'First Name'}),
            'last_name': forms.TextInput(attrs={'placeholder': 'Last Name'}),
            'phone_number':
            forms.TextInput(attrs={'placeholder': 'Phone Number'}),
        }

    def clean(self):
        cleaned_data = super(UserSignup, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(
                    "Passwords don't match. Please enter both fields again.")
        self.cleaned_data['first_name'] = self.cleaned_data[
            'first_name'].capitalize()
        self.cleaned_data['last_name'] = self.cleaned_data[
            'last_name'].capitalize()
        return self.cleaned_data

    def save(self, commit=True):
        user = super(UserSignup, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user
Пример #28
0
class RegistrationForm(forms.ModelForm):
    """
    Registration form, allows users to create accounts.
    """
    username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control'}),
                               label='')
    first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'First Name', 'class': 'form-control'}),
                                 label='')
    last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Last Name', 'class': 'form-control'}),
                                label='')
    password1 = PasswordField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control'}),
                              label='', validators=[LengthValidator(min_length=6),
                                                    ComplexityValidator(complexities=dict(UPPER=1, LOWER=1, DIGITS=1))])
    password2 = forms.CharField(
        widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password', 'class': 'form-control'}), label='')

    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'password1', 'password2']

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError("Email is already in use.")
        return username

    def clean(self):
        """
        Verifies that the values entered into the password fields match

        NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field.
        """
        cleaned_data = super(RegistrationForm, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("Passwords don't match. Please enter both fields again.")
        return self.cleaned_data

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        user_profile = None
        if commit:
            user.save()
            user_profile = UserProfile(user=user)
            user_profile.save()
        return user_profile
Пример #29
0
class RegForm(RegistrationForm):
    # modified from here: /usr/local/lib/python2.7/dist-packages/registration/forms.py
    username = forms.RegexField(
        regex=r'^[a-zA-Z0-9]+$',
        min_length=5,
        max_length=30,
        label=("Username"),
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        error_messages={
            'invalid': ("Username may contain only letters and numbers")
        },
        help_text=
        "Username may contain at least 5 alphanumeric characters with only letters and numbers "
    )

    email = forms.EmailField(
        validators=[ajiEmailValidator],
        label=("E-mail"),
        help_text=
        'Currently you can only register with gmail, hotmail, yahoo or .edu domain (i.e. @ntu.edu.tw).',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'type': 'email'
        }),
    )
    #    password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Password'}),
    #                                label=("Password"))
    password1 = PasswordField(
        label="Password",
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'type': 'password'
        }),
        help_text=
        "Password may contains at least 5 characters with not too simple sequence (i.e. 12345, qwerty)."
    )
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={
        'class': 'form-control',
        'type': 'password'
    }),
                                label=("Password (again)"))

    #    tos = forms.BooleanField(widget=forms.CheckboxInput,
    #                             label=(u'I have read and agree to the Terms of Service'),
    #                             error_messages={'required': ("You must agree to the terms to register")})
    captcha = CaptchaField()
Пример #30
0
class Registration_Form(ModelForm):

    cleaned_data = {}
    #  password = forms.CharField(widget=forms.PasswordInput)
    password = PasswordField(label="Password")
    confirm_password = forms.CharField(widget=forms.PasswordInput)
    captcha = CaptchaField()

    class Meta:
        model = VLAB_User
        fields = ['email', 'first_name', 'last_name', 'password', 'confirm_password', 'admitted_on', 'department',
                  'phone', 'captcha']

    def clean(self):
        cleaned_data = super(Registration_Form, self).clean()
        if 'password' in self.cleaned_data and 'confirm_password' in self.cleaned_data:
            if self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
                raise forms.ValidationError("Passwords don't match. Please enter both fields again.")
        return self.cleaned_data