Example #1
0
 def __init__(self, *args, **kwargs):
     super(CustomResetPasswordKeyForm, self).__init__(*args, **kwargs)
     self.fields['password1'] = PasswordField(label='Enter new password')
     self.fields['password2'] = PasswordField(label='Confirm new password')
     self.fields['password1'].widget.attrs['placeholder'] = ''
     self.fields['password2'].widget.attrs['placeholder'] = ''
     for fieldname, field in self.fields.items():
         field.widget.attrs.update({
             'class': 'w-full rounded border-gray-400 focus:border-brand focus:ring-0 transition my-1'
         })
Example #2
0
    def __init__(self, *args, **kwargs):
        super(CustomChangePasswordForm, self).__init__(*args, **kwargs)
        self.fields['oldpassword'] = PasswordField(label='رمز قبلی')
        self.fields['oldpassword'].widget = forms.PasswordInput(
            attrs={'class': 'form-control'})

        self.fields['password1'] = SetPasswordField(label='رمز جدید')
        self.fields['password1'].widget = forms.PasswordInput(
            attrs={'class': 'form-control'})

        self.fields['password2'] = PasswordField(label='تکرار رمز جدید')
        self.fields['password2'].widget = forms.PasswordInput(
            attrs={'class': 'form-control'})
Example #3
0
class UpdatedSignUpForm(SignupForm):
    password1 = PasswordField(label=_("Password"))
    password2 = PasswordField(label=_("Password (again)"))
    captcha = ReCaptchaField()

    def save(self, request):
        # Ensure you call the parent class's save.
        # .save() returns a User object.
        user = super(UpdatedSignUpForm, self).save(request)

        # Add your own processing here.

        # You must return the original result.
        return user
Example #4
0
class ChangePasswordForm(forms.Form):
    oldpassword = PasswordField(label=_("Current Password"))
    password1 = SetPasswordField(label=_("New Password"))
    password2 = PasswordField(label=_("New Password (again)"))

    def clean_password2(self):
        if ("password1" in self.cleaned_data
                and "password2" in self.cleaned_data):
            if (self.cleaned_data["password1"] !=
                    self.cleaned_data["password2"]):
                raise forms.ValidationError(
                    _("You must type the same password"
                      " each time."))
        return self.cleaned_data["password2"]
Example #5
0
class SignupForm(BaseSignupForm):
    password1 = PasswordField(label="비밀번호")
    password2 = PasswordField(label="비밀번호 확인")

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(SignupForm, self).__init__(*args, **kwargs)
        self.fields['email'].widget = forms.TextInput(attrs={
            'type': 'email',
            'placeholder': '이메일'
        })
        self.fields['email'].label = '이메일'
        self.fields['email'].error_messages['required'] = '이메일를 입력해주세요'

        self.fields['password1'].widget = forms.PasswordInput(
            attrs={'placeholder': '비밀번호(6자리 이상)'})
        self.fields['password1'].error_messages['required'] = '비밀번호를 입력해주세요'
        self.fields['password2'].widget = forms.PasswordInput(
            attrs={'placeholder': '비밀번호 확인'})
        self.fields['password2'].error_messages['required'] = '비밀번호 확인을 입력해주세요'

    def save(self, request):
        adapter = get_adapter(request)
        user = adapter.new_user(request)
        adapter.save_user(request, user, self)
        self.custom_signup(request, user)
        return user

    def clean(self):
        cleaned_data = super(SignupForm, 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("비밀번호가 서로 다릅니다. 확인 부탁드립니다.")
        return cleaned_data

    def raise_duplicate_email_error(self):
        email = self.cleaned_data['email']

        # 페이스북 계정이 이미 있는 경우
        is_social = SocialAccount.objects.filter(user__email=email).exists()
        if is_social:
            raise forms.ValidationError("페이스북으로 연결된 계정입니다. 페이스북 로그인을 이용해 주세요.")
        else:
            raise forms.ValidationError("이미 가입된 이메일입니다.")

    def custom_signup(self, request, user):
        password = self.cleaned_data["password1"]
        user.set_password(password)
        user.save()
Example #6
0
class CustomSignupForm(BaseSignupForm):

    password1 = SetPasswordField(label=_("Password"))
    password2 = PasswordField(label=_("Password (again)"))
    confirmation_key = forms.CharField(max_length=40,
                                       required=False,
                                       widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        super(CustomSignupForm, self).__init__(*args, **kwargs)
        if not app_settings.SIGNUP_PASSWORD_VERIFICATION:
            del self.fields["password2"]

    def clean(self):
        super(CustomSignupForm, self).clean()
        if app_settings.SIGNUP_PASSWORD_VERIFICATION \
                and "password1" in self.cleaned_data \
                and "password2" in self.cleaned_data:
            if self.cleaned_data["password1"] \
                    != self.cleaned_data["password2"]:
                raise forms.ValidationError(
                    _("You must type the same password each time."))
        return self.cleaned_data

    def save(self, request):
        adapter = get_adapter()
        user = adapter.new_user(request)
        adapter.save_user(request, user, self)
        self.custom_signup(request, user)
        # TODO: Move into adapter `save_user` ?
        setup_user_email(request, user, [])
        return user
Example #7
0
class AddEmailForm(CoreAddEmailForm):
    oldpassword = PasswordField(label='Súčasné heslo')

    def clean_oldpassword(self):
        if not self.user.check_password(self.cleaned_data.get("oldpassword")):
            raise forms.ValidationError("Zadajte prosím súčasné heslo")
        return self.cleaned_data["oldpassword"]
Example #8
0
    class StripeSubscriptionSignupForm(forms.Form):
        """
            Requires the following packages:

                * django-crispy-forms
                * django-floppyforms
                * django-allauth

            Necessary settings::

                INSTALLED_APPS += (
                    "floppyforms",
                    "allauth",  # registration
                    "allauth.account",  # registration
                )
                ACCOUNT_SIGNUP_FORM_CLASS = "djstripe.StripeSubscriptionSignupForm"

            Necessary URLS::

                (r'^accounts/', include('allauth.urls')),

        """
        username = forms.CharField(max_length=30)
        email = forms.EmailField(max_length=30)
        password1 = SetPasswordField(label=_("Password"))
        password2 = PasswordField(label=_("Password (again)"))
        confirmation_key = forms.CharField(max_length=40,
                                           required=False,
                                           widget=forms.HiddenInput())
        stripe_token = forms.CharField(widget=forms.HiddenInput())
        plan = forms.ChoiceField(choices=PLAN_CHOICES)

        # Stripe nameless fields
        number = forms.CharField(
            max_length=20,
            required=False,
            widget=StripeWidget(attrs={"data-stripe": "number"}))
        cvc = forms.CharField(
            max_length=4,
            label=_("CVC"),
            required=False,
            widget=StripeWidget(attrs={"data-stripe": "cvc"}))
        exp_month = forms.CharField(
            max_length=2,
            required=False,
            widget=StripeWidget(attrs={"data-stripe": "exp-month"}))
        exp_year = forms.CharField(
            max_length=4,
            required=False,
            widget=StripeWidget(attrs={"data-stripe": "exp-year"}))

        def save(self, user):
            try:
                customer, created = Customer.get_or_create(user)
                customer.update_card(self.cleaned_data["stripe_token"])
                customer.subscribe(self.cleaned_data["plan"])
            except stripe.StripeError as e:
                # handle error here
                raise e
Example #9
0
    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        self.fields['password1'] = PasswordField(label='رمز عبور')
        self.fields['password1'].widget = forms.PasswordInput(
            attrs={'class': 'form-control'})

        self.fields['password2'] = PasswordField(label='تکرار رمز عبور')
        self.fields['password2'].widget = forms.PasswordInput(
            attrs={'class': 'form-control'})

        self.fields['username'] = forms.CharField(
            label="نام کاربری",
            widget=forms.TextInput(attrs={'class': 'form-control'}))

        self.fields['email'] = forms.EmailField(
            label="ایمیل",
            widget=forms.EmailInput(attrs={'class': 'form-control'}))
Example #10
0
 def __init__(self, *args, **kwargs):
     super(SignupForm, self).__init__(*args, **kwargs)
     self.fields['password2'] = PasswordField(label=_("Confirm Password"))
     self.fields['email'] = EmailField(
         label=_('Email ID'),
         widget=forms.EmailInput(attrs={
             'class': 'form-control',
             'placeholder': 'Email ID'
         }))
Example #11
0
    def __init__(self, *args, **kwargs):
        super(CustomResetPasswordKeyForm, self).__init__(*args, **kwargs)
        self.fields['password1'] = SetPasswordField(label='رمز عبور')
        self.fields['password1'].widget = forms.PasswordInput(
            attrs={'class': 'form-control'})

        self.fields['password2'] = PasswordField(label='تکرار رمز عبور')
        self.fields['password2'].widget = forms.PasswordInput(
            attrs={'class': 'form-control'})
Example #12
0
class MyCustomChangePasswordForm(ChangePasswordForm):

    oldpassword = PasswordField(label=("Current Password"))
    password1 = SetPasswordField(label=("New Password"))
    password2 = PasswordField(label=("New Password (again)"))

    def __init__(self, *args, **kwargs):
        super(MyCustomChangePasswordForm, 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"])
Example #13
0
class ExtChangePasswordForm(ChangePasswordForm):
    oldpassword = PasswordField(label="Current Password")
    password1 = SetPasswordField(label="New Password")
    password2 = PasswordField(label="New Password (again)")

    def __init__(self, *args, **kwargs):
        super(ExtChangePasswordForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = "POST"
        self.helper.form_action = "/accounts/password/change/"
        self.helper.form_class = 'form'
        self.helper.form_id = 'auth_changepass'
        self.helper.layout = Layout(
            HTML(" {% csrf_token %} "),
            Div(Field('oldpassword',
                      css_class="input",
                      placeholder="Current Password",
                      autocomplete=False),
                HTML("<p id='oldpassword_error' class='help is-danger'></p >"),
                css_class="field"),
            Div(Field('password1',
                      css_class="input",
                      placeholder="New Password",
                      autocomplete=False),
                HTML("<p id='password1_error' class='help is-danger'></p >"),
                css_class="field"),
            Div(Field('password2',
                      css_class="input",
                      placeholder="New Password (again)",
                      autocomplete=False),
                HTML("<p id='password2_error' class='help is-danger'></p >"),
                css_class="field"),
            Div(
                HTML(
                    "<a id='pc_loader' class='button is-text is-loading is-hidden'></a>"
                ),
                Submit('submit',
                       'Change Password',
                       css_class="button is-info is-rounded",
                       css_id="pc_submit")))

    def save(self):
        super(ExtChangePasswordForm, self).save()
Example #14
0
class UserSignInForm(LoginForm):
    password = PasswordField(
        required=True,
        label="Password",
        autocomplete="current-password",
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Password',

        }))
Example #15
0
 def __init__(self, *args, **kwargs):
     super(CustomSignupForm, self).__init__(*args, **kwargs)
     self.fields['email'] = forms.EmailField(label='Email Address')
     self.fields['password2'] = PasswordField(label='Confirm password')
     self.fields['email'].widget.attrs['placeholder'] = 'Email'
     self.fields['password2'].widget.attrs['placeholder'] = 'Confirm password'
     self.fields['company_name'].widget.attrs['placeholder'] = 'Pizzeria Name'
     for fieldname, field in self.fields.items():
         field.widget.attrs.update({
             'class': 'w-full rounded border-gray-400 focus:border-brand focus:ring-0 transition my-1'
         })
Example #16
0
 def __init__(self, *args, **kwargs):
     super(CustomLoginForm, self).__init__(*args, **kwargs)
     # here you can change the fields
     # self.fields['username'] = forms.EmailField(label='custom label')
     # self.fields['login'] = forms.CharField(label="نام کاربری")
     self.fields['login'] = forms.CharField(
         label="نام کاربری",
         widget=forms.TextInput(attrs={'class': 'form-control'}))
     self.fields['password'] = PasswordField(label="پسوورد")
     self.fields['password'].widget = forms.PasswordInput(
         attrs={'class': 'form-control'})
Example #17
0
class UserForm(PasswordVerificationMixin, forms.ModelForm):

    password1 = PasswordField(label="New Password", required=False)
    password2 = PasswordField(label="New Password (again)", required=False)

    class Meta:
        model = User
        fields = ("name", "image", "bio", "email")

    def clean_password1(self):
        password = self.cleaned_data.get("password1")
        if password:
            get_adapter().clean_password(password, self.instance)
        return password

    def save(self):
        instance = super().save(commit=False)
        password = self.cleaned_data.get("password1")
        if password:
            get_adapter().set_password(instance, password)
        else:
            instance.save()
        return instance
Example #18
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Confirma tu contraseña
        self.fields['password2'] = PasswordField(label=_("Re-enter password"))

        for field in self.fields:
            self.fields[field].widget.attrs.pop("placeholder", None)

        self.helper = FormHelper()
        self.helper.layout = Layout(
            'email',
            'password1',
            'password2',
            HTML(CUSTOM_SIGNUP_SUBMIT),
        )
Example #19
0
class SocialForm(SignupForm):

    password1 = SetPasswordField(min_length=6, label='Enterpassword')
    password2 = PasswordField(min_length=6, label='Rente password again')

    def clean_password2(self):
        if ("password1" in self.cleaned_data
                and "password2" in self.cleaned_data):
            if (self.cleaned_data["password1"] !=
                    self.cleaned_data["password2"]):
                raise forms.ValidationError(("Password mismatch"))

    def signup(self, request, user):
        user.set_password(self.user, self.cleaned_data["password1"])
        user.save()
Example #20
0
class SignupForm(ProfileForm):
    email = forms.EmailField(required=True)
    password1 = SetPasswordField(label="Password", required=True)
    password2 = PasswordField(label="Password (again)", required=True)

    def clean_email(self):
        """
        Check if user is already registered and if so raise validation error.

        It may be considered a security hole to inform if a user
        is registered or not but it improves usability.
        """
        email = self.cleaned_data['email']
        User = get_user_model()
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('This email is already registered.')
        return email
Example #21
0
class ChangePasswordForm(UserForm):

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

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

    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'])
Example #22
0
class UserSetPasswordForm(PasswordVerificationMixin, forms.Form):
    """
    See allauth:
        https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py#L54
        If we do not want this dependency, we can write our own clean method to ensure the
        2 typed-in passwords match.
    """

    password1 = SetPasswordField(
        label="New Password",
        help_text=password_validation.password_validators_help_text_html(),
    )
    password2 = PasswordField(label="New Password (again)")

    def save(self, user):
        user.set_password(self.cleaned_data["password1"])
        user.has_valid_password = True
        user.save()

        return user
Example #23
0
class ResetPasswordKeyForm(ResetPasswordKeyForm):
    password1 = SetPasswordField(label="새 비밀번호")
    password2 = PasswordField(label="새 비밀번호 확인")

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        self.user = kwargs['user']
        self.temp_key = kwargs.pop("temp_key", None)
        super(ResetPasswordKeyForm, self).__init__(*args, **kwargs)

    def clean_password2(self):
        if ("password1" in self.cleaned_data
                and "password2" in self.cleaned_data):
            if (self.cleaned_data["password1"] !=
                    self.cleaned_data["password2"]):
                raise forms.ValidationError("비밀번호가 서로 다릅니다. 다시 확인해주세요.")
        return self.cleaned_data["password2"]

    def save(self):
        get_adapter().set_password(self.user, self.cleaned_data["password1"])
Example #24
0
class CustomResetPasswordKeyForm(ResetPasswordKeyForm):
    """Reset Password with Key Form.

    Attributes:
        helper (TYPE): Description
    """

    password1 = SetPasswordField(label="Nueva contraseña")
    password2 = PasswordField(label="Nueva contraseña ( Otra vez)")
    helper = FormHelper()
    helper.form_tag = False

    def __init__(self, *args, **kwargs):
        """Reset Password with Key Form.

        Args:
            *args (TYPE): Description
            **kwargs (TYPE): Description
        """
        super(CustomResetPasswordKeyForm, self).__init__(*args, **kwargs)
Example #25
0
class CustomLoginForm(LoginForm):
    """Custom login form.

    Attributes:
        helper (TYPE): Description
    """

    password = PasswordField(label="contraseña")
    login = forms.CharField(required=True, label="Correo electrónico")
    helper = FormHelper()
    helper.form_tag = False

    def __init__(self, *args, **kwargs):
        """Custom login form.

        Args:
            *args (TYPE): Description
            **kwargs (TYPE): Description
        """
        super(CustomLoginForm, self).__init__(*args, **kwargs)
Example #26
0
class CustomLoginForm(LoginForm):
    password = PasswordField(label=("رمز عبور"))
    error_messages = {
        'account_inactive': ("این حساب در حال حاضر غیرفعال است ."),
        'email_password_mismatch':
        ("آدرس ایمیل یا رمز عبور وارد شده اشتباه است ."),
        'username_password_mismatch': ("نام کابری یا رمز عبور اشتباه است ."),
    }

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(CustomLoginForm, self).__init__(*args, **kwargs)
        login_widget = forms.TextInput(attrs={
            'placeholder': ('نام کاربری'),
            'autofocus': 'autofocus'
        })
        username = forms.CharField(label=("نام کاربری"),
                                   widget=login_widget,
                                   max_length=100)

        self.fields["login"] = username
Example #27
0
class CustomChangePasswordForm1(forms.ModelForm):
    """Change Password Form.

    Attributes:
        helper (TYPE): Description
    """

    password = SetPasswordField(label="Contraseña")
    repeat_password = PasswordField(label="Confirmar contraseña")

    helper = FormHelper()
    helper.form_tag = False

    helper.layout = Layout(
        Div(
            'password',
            css_class='col-md-12',
            style="",
        ),
        Div('repeat_password', css_class='col-md-12'),
        Div('email', css_class='col-md-6', hidden="true"),
    )

    class Meta:
        """Meta.

        Attributes:
            exclude (list): Description
            model (TYPE): Description
        """

        model = User
        exclude = ['first_name', 'last_name', 'user_type', 'is_active']

    def __init__(self, *args, **kwargs):
        """."""
        super(CustomChangePasswordForm1, self).__init__(*args, **kwargs)
Example #28
0
class LoginForm(forms.Form):

    password = PasswordField(label=_("Password"))
    remember = forms.BooleanField(label=_("Remember Me"), required=False)

    user = None
    error_messages = {
        'account_inactive':
        _("This account is currently inactive."),
        'email_password_mismatch':
        _("The e-mail address and/or password you specified are not correct."),
        'username_password_mismatch':
        _("The username and/or password you specified are not correct."),
        'username_email_password_mismatch':
        _("The login and/or password you specified are not correct.")
    }

    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL:
            login_widget = forms.TextInput(
                attrs={
                    'type': 'email',
                    'placeholder': _('E-mail address'),
                    'autofocus': 'autofocus'
                })
            login_field = forms.EmailField(label=_("E-mail"),
                                           widget=login_widget)
        elif app_settings.AUTHENTICATION_METHOD \
                == AuthenticationMethod.USERNAME:
            login_widget = forms.TextInput(attrs={
                'placeholder': _('Username'),
                'autofocus': 'autofocus'
            })
            login_field = forms.CharField(label=_("Username"),
                                          widget=login_widget,
                                          max_length=get_username_max_length())
        else:
            assert app_settings.AUTHENTICATION_METHOD \
                == AuthenticationMethod.USERNAME_EMAIL
            login_widget = forms.TextInput(
                attrs={
                    'placeholder': _('Username or e-mail'),
                    'autofocus': 'autofocus'
                })
            login_field = forms.CharField(label=pgettext(
                "field label", "Login"),
                                          widget=login_widget)
        self.fields["login"] = login_field
        set_form_field_order(self, ["login", "password", "remember"])
        if app_settings.SESSION_REMEMBER is not None:
            del self.fields['remember']

    def user_credentials(self):
        """
        Provides the credentials required to authenticate the user for
        login.
        """
        credentials = {}
        login = self.cleaned_data["login"]
        if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL:
            credentials["email"] = login
        elif (app_settings.AUTHENTICATION_METHOD ==
              AuthenticationMethod.USERNAME):
            credentials["username"] = login
        else:
            if "@" in login and "." in login:
                credentials["email"] = login
            credentials["username"] = login
        credentials["password"] = self.cleaned_data["password"]
        return credentials

    def clean_login(self):
        login = self.cleaned_data['login']
        return login.strip()

    def clean(self):
        if self._errors:
            return
        user = authenticate(**self.user_credentials())
        if user:
            self.user = user
        else:
            raise forms.ValidationError(
                self.error_messages['%s_password_mismatch' %
                                    app_settings.AUTHENTICATION_METHOD])
        return self.cleaned_data

    def login(self, request, redirect_url=None):
        ret = perform_login(request,
                            self.user,
                            email_verification=app_settings.EMAIL_VERIFICATION,
                            redirect_url=redirect_url)
        remember = app_settings.SESSION_REMEMBER
        if remember is None:
            remember = self.cleaned_data['remember']
        if remember:
            request.session.set_expiry(app_settings.SESSION_COOKIE_AGE)
        else:
            request.session.set_expiry(0)
        return ret
Example #29
0
class SignupForm(forms.Form):

    username = forms.CharField(max_length=80, required=True)
    email = forms.EmailField(required=True)
    password1 = SetPasswordField()
    password2 = PasswordField()
    language = forms.TypedChoiceField(
        choices=settings.LANGUAGE_CHOICES,
        widget=forms.Select(attrs={'class': 'input-lg'}),
        required=True)
    topic1 = forms.ModelChoiceField(
        queryset=Topic.objects.all(),
        widget=forms.Select(attrs={'class': 'input-lg'}),
        empty_label='Select topic')
    choice1 = forms.ChoiceField(choices=(('pro', "I agree with this."),
                                         ('against', "I disagree with this.")),
                                widget=forms.RadioSelect())
    topic2 = forms.ModelChoiceField(
        queryset=Topic.objects.all(),
        widget=forms.Select(attrs={'class': 'input-lg'}),
        empty_label='Select topic')
    choice2 = forms.ChoiceField(choices=(('pro', "I agree with this."),
                                         ('against', "I disagree with this.")),
                                widget=forms.RadioSelect())
    topic3 = forms.ModelChoiceField(
        queryset=Topic.objects.all(),
        widget=forms.Select(attrs={'class': 'input-lg'}),
        empty_label='Select topic')
    choice3 = forms.ChoiceField(choices=(('pro', "I agree with this."),
                                         ('against', "I disagree with this.")),
                                widget=forms.RadioSelect())
    topic4 = forms.ModelChoiceField(
        queryset=Topic.objects.all(),
        widget=forms.Select(attrs={'class': 'input-lg'}),
        empty_label='Select topic')
    choice4 = forms.ChoiceField(choices=(('pro', "I agree with this."),
                                         ('against', "I disagree with this.")),
                                widget=forms.RadioSelect())

    class Meta:
        model = get_user_model()  # use this function for swapping user model
        fields = ('email', 'username', 'password1', 'password2', 'language')

    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'signup_form'
        self.helper.label_class = 'col-xs-6'
        self.helper.field_class = 'col-xs-12'
        self.helper.form_method = 'post'
        self.helper.form_action = 'accounts_signup'
        self.helper.add_input(Submit('submit', 'Sign up'))

    def signup(self, request, user):
        user.username = self.cleaned_data['username']
        user.email = self.cleaned_data['email']
        user.language = self.cleaned_data['language']
        topic1 = Topic.objects.get(title=self.cleaned_data['topic1'])
        choice1 = self.cleaned_data['choice1']
        if choice1 == "pro":
            user.topics_pro.add(topic1)
        else:
            user.topics_against.add(topic1)
        topic2 = Topic.objects.get(title=self.cleaned_data['topic2'])
        choice2 = self.cleaned_data['choice2']
        if choice2 == "pro":
            user.topics_pro.add(topic2)
        else:
            user.topics_against.add(topic2)
        topic3 = Topic.objects.get(title=self.cleaned_data['topic3'])
        choice3 = self.cleaned_data['choice3']
        if choice3 == "pro":
            user.topics_pro.add(topic3)
        else:
            user.topics_against.add(topic3)
        topic4 = Topic.objects.get(title=self.cleaned_data['topic4'])
        choice4 = self.cleaned_data['choice4']
        if choice4 == "pro":
            user.topics_pro.add(topic4)
        else:
            user.topics_against.add(topic4)
        user.save()
Example #30
0
 def __init__(self, *args, **kwargs):
     super(CustomSignupForm, self).__init__(*args, **kwargs)
     self.fields['password1'] = PasswordField(label=("رمز عبور"))
     self.fields['password2'] = PasswordField(label=("تکرار رمز عبور"))
     self.fields['email'].label = gettext("ایمیل")