Ejemplo n.º 1
0
class LoginForm(LoginForm):
    """
    Login form for users.
    This form extented from `allauth.account.forms.LoginForm`
    And updating the form for google `captcha`.
    """
    error_message = {'username_not_exist': _("User is not registered!")}

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

    if not settings.DEBUG:
        captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
            attrs={
                'data-theme': 'light',
                'data-size': 'normal',
                # 'style': ('transform:scale(1.057);-webkit-transform:scale(1.057);'
                #           'transform-origin:0 0;-webkit-transform-origin:0 0;')
            }))

    def clean_login(self):
        username = self.cleaned_data.get('login')
        if not User.objects.filter(username=username).exists():
            raise forms.ValidationError(
                self.error_message['username_not_exist'],
                code='username_not_exist',
            )
        return username
Ejemplo n.º 2
0
class AuthenticationForm(auth_forms.AuthenticationForm):
    captcha = ReCaptchaField(
        label=False, widget=ReCaptchaV2Checkbox(attrs={'data-theme': 'dark'}))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.pop('autofocus')
Ejemplo n.º 3
0
class CommentForm(forms.ModelForm):

	name = forms.CharField(label='', widget=forms.TextInput(attrs={
		'class': 'form-control',
		'placeholder': 'Type your name',
		'id': 'username',

		}))

	comment = forms.CharField(label='', widget=forms.Textarea(attrs={
		'class': 'form-control',
		'placeholder': 'Type your comment ',
		'id': 'usercomment',
		'rows': 5,

		}))

	captcha = ReCaptchaField(label='', widget=ReCaptchaV2Checkbox(attrs={
			'class': 'post-captcha',
            'data-theme': 'light',
        }))

	class Meta:
		model = Comment
		fields = ('name', 'comment', )
Ejemplo n.º 4
0
class AnwserProposeForm(forms.Form):
    text = forms.CharField(label='Tekst odpowiedź')
    make_new_statement = forms.BooleanField(required=False,
                                            label='Nowa wypowiedź')
    new_statement = forms.CharField(label="Tekst nowej odpowiedzi",
                                    widget=forms.Textarea,
                                    required=False)
    goto_statement = forms.CharField(
        label="ID wypowiedzi",
        max_length=128,
        required=False,
        widget=forms.TextInput(
            attrs={'placeholder': 'Znajdziejsz na dole strony'}))
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
        attrs={'data-callback': 'enableSubmit'}))

    def clean(self):
        cleaned_data = super().clean()
        if not cleaned_data.get("captcha"):
            raise forms.ValidationError("Sprawdź czy nie jesteś robotem :)")

        make_new_statement = cleaned_data.get("make_new_statement")
        if make_new_statement:
            new_statement = cleaned_data.get("new_statement")
            if len(new_statement) < 1:
                raise forms.ValidationError(
                    "Jeśli wybrano nowe zdanie to należy je podać")
        else:
            try:
                goto_statement = cleaned_data.get("goto_statement")
                s = Statement.objects.get(id=goto_statement)
            except Exception as e:
                raise forms.ValidationError(
                    "W trakcie odnajdywania zdania napotkono błąd: {}".format(
                        e))
Ejemplo n.º 5
0
 def __init__(self, *args, **kwargs):
     self.user = kwargs.pop('instance', None)
     force_required = kwargs.pop('force_required', False)
     super(SignupForm, self).__init__(*args, **kwargs)
     self.fields['type'] = forms.ChoiceField(choices=[
         (slugify(choice[1]), choice[1])
         for choice in Organization.ACCOUNT_TYPE
     ],
                                             required=False)
     if getattr(get_current_app(), 'registration_requires_recaptcha',
                False):
         # Default captcha field is already appended at the end of the list
         # of fields. We overwrite it here to set the theme.
         self.fields['captcha'] = ReCaptchaField(widget=ReCaptchaV2Checkbox(
             attrs={
                 'data-theme': 'clean',
                 'data-size': 'compact',
             }))
     if 'country' in self.fields:
         # Country field is optional. We won't add a State/Province
         # in case it is omitted.
         if not ('country' in self.initial and self.initial['country']):
             self.initial['country'] = Country("US", None)
         country = self.initial.get('country', None)
         if not self.fields['country'].initial:
             self.fields['country'].initial = country.code
         self.add_postal_region(country=country)
     for extra_field in self.initial.get('extra_fields', []):
         # define extra fields dynamically:
         self.fields[extra_field[0]] = forms.CharField(
             label=_(extra_field[1]), required=extra_field[2])
     if force_required:
         for field_name, field in six.iteritems(self.fields):
             if field_name not in ('organization_name', 'type'):
                 field.required = True
Ejemplo n.º 6
0
class BubbleCreateForm(BubbleChangeForm):

    password2 = forms.CharField(
        max_length=20,
        widget=forms.PasswordInput(attrs={
            'placeholder': 'Repeat password',
            'autocomplete': 'new-password'
        }))
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
        api_params={'onload': 'adjustHeight'}))

    prefix = 'create'

    class Meta(BubbleChangeForm.Meta):
        fields = ('name', 'email', 'password1', 'password2', 'public',
                  'captcha')
        help_texts = {
            'email':
            'Used solely to send you a password\nreset link and let others contact\nyou in case they forgot the password.',
            'public':
            'Your bubble can be accessed without password and thus easily shared via link. Adding questions still requires password. Will be listed in public bubbles list. Can be changed in bubble settings.'
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password1'].required = True
        self.fields['password2'].required = True

    def clean(self):
        cleaned_data = super(BubbleCreateForm, self).clean()
        bubble = Bubble.objects.filter(name=cleaned_data.get('name', None))
        if bubble and bubble[0].id != self.instance.id:
            self.add_error('name', 'Name already in use')
        return cleaned_data
Ejemplo n.º 7
0
def get_recaptcha_widget():
    from captcha.widgets import (
        ReCaptchaV2Checkbox,
        ReCaptchaV2Invisible,
        ReCaptchaV3,
    )
    captcha_attrs = {}
    captcha_params = {}
    try:
        captcha_attrs = settings.EMAILER_RECAPTCHA_ATTRS
    except AttributeError:
        pass
    try:
        captcha_params = settings.EMAILER_RECAPTCHA_PARAMS
    except AttributeError:
        pass
    widget_dict = {
        1: ReCaptchaV2Checkbox(attrs=captcha_attrs, api_params=captcha_params),
        2: ReCaptchaV2Invisible(attrs=captcha_attrs,
                                api_params=captcha_params),
        3: ReCaptchaV3(attrs=captcha_attrs, api_params=captcha_params),
    }
    try:
        widget_type = settings.EMAILER_RECAPTCHA_TYPE
    except AttributeError:
        widget_type = 1
    return widget_dict[widget_type]
Ejemplo n.º 8
0
class CartSubmitOrder(forms.Form):
    """Форма сабмита заказа"""
    _contact = get_config()['contactTypeList']

    contacts = [(key, value) for key, value in _contact.items()]

    contact_name = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'uk-input',
        'id': 'contact_name'
    }),
                                   min_length=3,
                                   max_length=255,
                                   label='Введите ваше имя')
    contact_type = forms.ChoiceField(
        widget=forms.widgets.Select(attrs={
            'id': 'contact_type',
            'class': 'uk-select'
        }),
        choices=tuple(contacts),
        label='Выберите удобный способ связи')
    contact_data = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'uk-input',
        'id': 'contact_data'
    }),
                                   min_length=4,
                                   max_length=512,
                                   label='Введите контактные данные')
    captcha = ReCaptchaField(
        widget=ReCaptchaV2Checkbox(attrs={'id': 'captcha'}), label='')
Ejemplo n.º 9
0
 def __init__(self, *args, **kwargs):
     super(ContactForm, self).__init__(*args, **kwargs)
     if not kwargs.get('initial', {}).get('email', None):
         if getattr(get_current_app(), 'contact_requires_recaptcha', False):
             self.fields['captcha'] = ReCaptchaField(
                 widget=ReCaptchaV2Checkbox(attrs={
                     'data-theme': 'clean',
                     'data-size': 'compact',
                 }))
Ejemplo n.º 10
0
class SignupWithCaptchaForm(NameEmailForm):

    username = forms.SlugField(max_length=30, label="Username")
    new_password = forms.CharField(widget=forms.PasswordInput(
        attrs={'placeholder': 'Password'}), label="Password")
    new_password2 = forms.CharField(widget=forms.PasswordInput(
        attrs={'placeholder': 'Type Password Again'}),
        label="Password confirmation")
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
        attrs={'data-size': 'compact'}))
Ejemplo n.º 11
0
class SignupForm(UserCreationForm):
    email = forms.EmailField()
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(attrs={
        'data-theme': 'dark',
    }),
                             required=True)

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2', 'captcha']
Ejemplo n.º 12
0
class AuthAdminForm(AuthenticationForm):

    if not settings.DEBUG:
        captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
            attrs={
                'data-theme': 'light',
                'data-size': 'normal',
                # 'style': ('transform:scale(1.057);-webkit-transform:scale(1.057);'
                #           'transform-origin:0 0;-webkit-transform-origin:0 0;')
            }))
Ejemplo n.º 13
0
class UserCreationForm(auth_forms.UserCreationForm):
    captcha = ReCaptchaField(
        label=False, widget=ReCaptchaV2Checkbox(attrs={'data-theme': 'dark'}))

    class Meta:
        model = models.User
        fields = ('email', 'name', 'password1', 'password2', 'captcha')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['email'].widget.attrs.pop('autofocus')
Ejemplo n.º 14
0
class SuggestionForm(forms.ModelForm):
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
        attrs={"data-theme": "dark"}))
    suggestion_text = forms.TextInput(attrs={"required": True})
    contact_email = forms.EmailField(widget=forms.EmailInput(
        attrs={"class": "contact-form"}))

    class Meta:
        model = Suggestion
        fields = ["suggestion_text", "contact_email"]
        widgets = {"tags": admin.widgets.AdminTextareaWidget}
Ejemplo n.º 15
0
class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()  # Define the new property and its rules
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(attrs={
        'data-theme': 'light',
    }))

    class Meta:
        model = User  # Model to be affected
        fields = [  # Fields you want to be displayed
            'username', 'email', 'first_name', 'last_name', 'password1',
            'password2'
        ]
Ejemplo n.º 16
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if settings.RECAPTCHA_PUBLIC_KEY:
            from captcha.fields import ReCaptchaField
            from captcha.widgets import ReCaptchaV2Checkbox

            self.fields["captcha"] = ReCaptchaField(widget=ReCaptchaV2Checkbox(
                attrs={
                    "data-theme": "light",
                    "data-size": "normal",
                }, ), )
Ejemplo n.º 17
0
class RegistroForm(forms.Form):
    nombres = forms.CharField(
        label="Nombres",
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Escribe tus nombres'
        }),
        max_length=100)

    apellidos = forms.CharField(
        label="Apellidos",
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Escribe tus apellidos'
        }),
        max_length=100)

    pais = forms.CharField(label="Pais",
                           required=True,
                           widget=forms.Select(choices=PAISES))
    fecha_nacimiento = forms.DateField(label="Fecha de nacimiento",
                                       required=False,
                                       widget=forms.SelectDateWidget(
                                           months=months,
                                           years=years,
                                           empty_label=("Año", "Mes", "Día"),
                                       ))  #campo opcional
    email = forms.EmailField(
        label="Email",
        required=True,
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': 'Escribe tu email'
        }),
        max_length=100,
        min_length=3)  #campo opcional

    genero = forms.CharField(label="Genero",
                             required=False,
                             widget=forms.Select(choices=GENEROS))
    contraseña = forms.CharField(label="Contraseña",
                                 required=True,
                                 widget=forms.PasswordInput())

    captcha = ReCaptchaField(
        public_key='6LdaUqcUAAAAAOK3xzjo-oknTM33fbXExlcwFG0z',
        private_key='6LdaUqcUAAAAANtBkskWrDSPz2SezQT_i3jsSRon',
        widget=ReCaptchaV2Checkbox())
Ejemplo n.º 18
0
class AstroBinRegistrationForm(RegistrationFormUniqueEmail,
                               RegistrationFormTermsOfService):
    referral_code = forms.fields.CharField(
        required=False,
        label=_(u'Referral code (optional)'),
    )

    important_communications = forms.fields.BooleanField(
        widget=forms.CheckboxInput,
        required=False,
        label=_(
            u'I accept to receive rare important communications via email'),
        help_text=
        _(u'This is highly recommended. These are very rare and contain information that you probably want to have.'
          ))

    newsletter = forms.fields.BooleanField(
        widget=forms.CheckboxInput,
        required=False,
        label=_(u'I accept to receive occasional newsletters via email'),
        help_text=
        _(u'Newsletters do not have a fixed schedule, but in any case they are not sent out more often than once per month.'
          ))

    marketing_material = forms.fields.BooleanField(
        widget=forms.CheckboxInput,
        required=False,
        label=
        _(u'I accept to receive occasional marketing and commercial material via email'
          ),
        help_text=
        _(u'These emails may contain offers, commercial news, and promotions from AstroBin or its partners.'
          ))

    recaptcha = ReCaptchaField(label=_('Are you a robot?'),
                               widget=ReCaptchaV2Checkbox(attrs={
                                   'data-theme': 'dark',
                               }))

    def clean(self):
        username_value = self.cleaned_data.get(User.USERNAME_FIELD)
        if username_value is not None and User.objects.filter(
                username__iexact=username_value).exists():
            self.add_error(
                User.USERNAME_FIELD,
                _(u'Sorry, this username already exists with a different capitalization.'
                  ))

        super(AstroBinRegistrationForm, self).clean()
Ejemplo n.º 19
0
class RegistrationForm(RegistrationFormUniqueEmail):
    email = forms.EmailField(widget=forms.EmailInput(attrs={
        'class': 'form-control',
        'placeholder': 'E-Mail'
    }),
                             required=True)
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
        attrs={'data-theme': 'light'}))
    password1 = forms.CharField(label="Password",
                                widget=forms.PasswordInput(
                                    attrs={
                                        'class': 'form-control',
                                        'placeholder': 'Password',
                                        'autocomplete': 'off'
                                    }))
    password2 = forms.CharField(label="Confirm Password",
                                widget=forms.PasswordInput(
                                    attrs={
                                        'class': 'form-control',
                                        'placeholder': 'Verify Password',
                                        'autocomplete': 'off'
                                    }))

    class Meta:
        model = User
        fields = ("username", "email", "first_name", "last_name")
        widgets = {
            'username':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'User Name'
            }),
            'email':
            forms.EmailInput(attrs={
                'class': 'form-control',
                'placeholder': 'E-Mail'
            }),
            'first_name':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'First Name'
            }),
            'last_name':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Last Name'
            }),
        }
Ejemplo n.º 20
0
class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['email']

    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
        attrs={'data-callback': 'enableFormSubmit'}),
                             label='')

    def __init__(self, *args, **kwargs):
        super(CreateUserForm, self).__init__(*args, **kwargs)

        self.fields['email'].widget.attrs.pop('autofocus')

        for fieldname in ['password1', 'password2']:
            self.fields[fieldname].help_text = None
Ejemplo n.º 21
0
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('target_user', None)
        super(EventCreateForm, self).__init__(*args, **kwargs)
        print('ran')
        if user.night_mode_enabled:
            captcha_theme = 'dark'
        else:
            captcha_theme = 'light'

        self.fields['captcha'] = ReCaptchaField(
            widget=ReCaptchaV2Checkbox(
                attrs={
                    'data-theme': f'{captcha_theme}'
                }
            )
        )
Ejemplo n.º 22
0
def login_user(request):
    if request.user.is_authenticated:
        if request.POST.get('next') is not None:
            return redirect(request.POST.get('next'))
        return redirect('dashboard')
    else:
        a = ReCaptchaField(widget=ReCaptchaV2Checkbox())
        if request.method == "POST":
            if 'g-recaptcha-response' in request.POST:
                try:
                    a.validate(request.POST.get('g-recaptcha-response'))
                except:
                    return render(
                        request, "system/user/login.html", {
                            'error': _("Invalid Captcha Error"),
                            "recaptcha": a.widget.render('recaptcha', '')
                        })
            user = auth.authenticate(username=request.POST.get('username'),
                                     password=request.POST.get('password'))
            if user is not None:
                if user.is_active:
                    auth.login(request, user)
                    if request.GET.get('next') is not None:
                        return redirect(request.GET.get('next'))
                    else:
                        return redirect('dashboard')
                else:
                    return render(
                        request, "system/user/login.html", {
                            'error': _("You are not allowed to access"),
                            "recaptcha": a.widget.render('recaptcha', '')
                        })
            else:
                return render(
                    request, "system/user/login.html", {
                        'error':
                        _("Username or Password you entered is wrong"),
                        "recaptcha": a.widget.render('recaptcha', '')
                    })
        else:

            return render(
                request,
                "system/user/login.html",
                context={"recaptcha": a.widget.render('recaptcha', '')})
Ejemplo n.º 23
0
class ContactFormHome(forms.Form):
    name = forms.CharField(
        label="Ваше имя*",
        widget=forms.TextInput(attrs={'class': 'input__contacts'}))

    email = forms.EmailField(
        label="E-mail*",
        widget=forms.EmailInput(attrs={'class': 'input__contacts'}))

    message = forms.CharField(
        label="Сообщение*",
        widget=forms.Textarea(attrs={'class': 'message__contacts'}))

    captcha = ReCaptchaField(label="",
                             widget=ReCaptchaV2Checkbox(attrs={
                                 'data-theme': 'light',
                                 'data-size': 'normal'
                             }))
Ejemplo n.º 24
0
class ResetPasswordForm(ResetPasswordForm):
    """
    Reset password form for users.
    This form extented from `allauth.account.forms.ResetPasswordForm`
    And updating the form for google `captcha`.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = kwargs.pop('request', None)

    if not settings.DEBUG:
        captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
            attrs={
                'data-theme': 'light',
                'data-size': 'normal',
                # 'style': ('transform:scale(1.057);-webkit-transform:scale(1.057);'
                #           'transform-origin:0 0;-webkit-transform-origin:0 0;')
            }))
Ejemplo n.º 25
0
class CommentForm(forms.ModelForm):
    captcha = ReCaptchaField(
        widget=ReCaptchaV2Checkbox(attrs={
            'theme': 'clean',
            'data-callback': "enableBtn"
        }),
        label='Проверка, что вы настоящий человек',
        required=True)

    class Meta:
        model = Comment
        fields = ('name', 'body', 'positiv', 'negativ')
        widgets = {
            'name':
            forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Введите ваше имя'
            }),
            'body':
            forms.Textarea(attrs={
                'class': 'form-control ',
                'rows': '4'
            }),
            'positiv':
            forms.Textarea(
                attrs={
                    'class': 'form-control',
                    'placeholder': 'Ваши позитивные впечатления',
                    'rows': '3'
                }),
            'negativ':
            forms.Textarea(
                attrs={
                    'class': 'form-control',
                    'placeholder': 'Ваши негативные впечатления',
                    'rows': '3'
                })
        }
        labels = {
            'name': 'Имя',
            'body': 'Ваш отзыв',
            'positiv': 'Достоинства',
            'negativ': 'Недостатки',
        }
Ejemplo n.º 26
0
class ContactForm(forms.Form):
    email = forms.EmailField(label=_('E-mail'))
    sender = forms.CharField(label=_('Sender'), max_length=20)
    subject = forms.CharField(label=_('Subject'), max_length=100)
    message = forms.CharField(label=_('Message'), widget=forms.Textarea)

    if not settings.DEBUG:
        captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
            attrs={
                'data-theme': 'light',
                'data-size': 'normal',
                # 'style': ('transform:scale(1.057);-webkit-transform:scale(1.057);'
                #           'transform-origin:0 0;-webkit-transform-origin:0 0;')
            }))

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super().__init__(*args, **kwargs)

        # use the selection email when user has logged in
        user = self.request.user
        if user.is_authenticated:
            if hasattr(user, 'emailaddress_set'):
                emails = user.emailaddress_set.values_list('email', 'email')
                if emails.exists():
                    self.fields['email'] = forms.ChoiceField(label=_('E-mail'),
                                                             choices=emails)

            # setting up the sender
            self.fields['sender'].initial = self.request.user

            # deleting the captcha
            if 'captcha' in self.fields:
                del self.fields['captcha']

        # updating the html class
        for (k, v) in self.fields.items():
            attrs = {'class': 'form-control text-normal'}
            if k == 'message':
                attrs.update({'rows': 5})

            if k != 'captcha':
                self.fields[k].widget.attrs = attrs
Ejemplo n.º 27
0
class AddressForm(forms.Form):
    shipping_address = forms.CharField(max_length=50, required=False)
    shipping_address_2 = forms.CharField(max_length=50, required=False)
    shipping_post_code = forms.CharField(max_length=10, required=False)

    set_default_shipping = forms.BooleanField(required=False)
    use_default_shipping = forms.BooleanField(required=False)
    old_cost_before_post = forms.CharField(max_length=32)
    captcha = ReCaptchaField(
        widget=ReCaptchaV2Checkbox()
    )

    def clean(self):
        cleaned_data = super().clean()
        shipping_address = cleaned_data.get('shipping_address')
        shipping_address_2 = cleaned_data.get('shipping_address_2')
        shipping_post_code = cleaned_data.get('shipping_post_code')
        use_default_shipping = cleaned_data.get('use_default_shipping')
        if any((not shipping_address, not shipping_address_2, not shipping_post_code)) and (
                not use_default_shipping):
            raise forms.ValidationError('使用默认地址或者填写有效的地址')
Ejemplo n.º 28
0
class CommentForm(forms.ModelForm):
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox())

    class Meta:
        model = PostPageComments
        fields = ['new_comment']
Ejemplo n.º 29
0
class SefariaNewUserForm(EmailUserCreationForm):
    email = forms.EmailField(
        max_length=75,
        widget=forms.EmailInput(attrs={
            'placeholder': _("Email Address"),
            'autocomplete': 'off'
        }))
    first_name = forms.CharField(widget=forms.TextInput(
        attrs={
            'placeholder': _("First Name"),
            'autocomplete': 'off'
        }))
    last_name = forms.CharField(widget=forms.TextInput(
        attrs={
            'placeholder': _("Last Name"),
            'autocomplete': 'off'
        }))
    password1 = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'placeholder': _("Password"),
            'autocomplete': 'off'
        }))
    subscribe_educator = forms.BooleanField(label=_("I am an educator"),
                                            help_text=_("I am an educator"),
                                            initial=False,
                                            required=False)

    captcha_lang = "iw" if get_language() == 'he' else "en"
    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox(
        attrs={'data-theme': 'white'
               #'data-size': 'compact',
               },
        #api_params={'hl': captcha_lang}
    ))

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

    def __init__(self, *args, **kwargs):
        super(EmailUserCreationForm, self).__init__(*args, **kwargs)
        del self.fields['password2']
        self.fields.keyOrder = [
            "email", "first_name", "last_name", "password1", "captcha"
        ]
        self.fields.keyOrder.append("subscribe_educator")

    def clean_email(self):
        email = self.cleaned_data["email"]
        if user_exists(email):
            user = get_user(email)
            if not user.groups.filter(name=SEED_GROUP).exists():
                raise forms.ValidationError(
                    _("A user with that email already exists."))
        return email

    def save(self, commit=True):
        email = self.cleaned_data["email"]
        if user_exists(email):
            # A 'User Seed' existing for this email address.
            user = get_user(email)
            user.set_password(self.cleaned_data["password1"])
            seed_group = Group.objects.get(name=SEED_GROUP)
            user.groups.remove(seed_group)
        else:
            user = super(SefariaNewUserForm, self).save(commit=False)

        user.first_name = self.cleaned_data["first_name"]
        user.last_name = self.cleaned_data["last_name"]

        if commit:
            user.save()

        mailingLists = []
        language = get_language()

        list_name = "Announcements_General_Hebrew" if language == "he" else "Announcements_General"
        mailingLists.append(list_name)

        if self.cleaned_data["subscribe_educator"]:
            list_name = "Announcements_Edu_Hebrew" if language == "he" else "Announcements_Edu"
            mailingLists.append(list_name)

        if mailingLists:
            mailingLists.append("Signed_Up_on_Sefaria")
            try:
                subscribe_to_list(mailingLists,
                                  user.email,
                                  first_name=user.first_name,
                                  last_name=user.last_name)
            except:
                pass

        return user
Ejemplo n.º 30
0
class RegistroForm(forms.Form):

    Tipo_de_identificacion = forms.CharField(
        label="ID",
        required=True,
        widget=forms.Select(attrs={'class': 'form-control'},
                            choices=IDENTIFICACION))
    DNI = forms.CharField(
        label="DNI",
        required=True,
        max_length=10,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Escribe tu DNI'
        }))

    nombres = forms.CharField(label="Nombres",
                              required=True,
                              widget=forms.TextInput(
                                  attrs={
                                      'class': 'form-control',
                                      'placeholder': 'Escribe tus nombres',
                                      'id': 'custom'
                                  }),
                              max_length=100)

    apellidos = forms.CharField(label="Apellidos",
                                required=True,
                                widget=forms.TextInput(
                                    attrs={
                                        'class': 'form-control',
                                        'placeholder': 'Escribe tus apellidos',
                                        'id': 'app'
                                    }),
                                max_length=100)

    pais = forms.CharField(label="Pais",
                           required=True,
                           widget=forms.Select(choices=PAISES,
                                               attrs={
                                                   'class':
                                                   'form-control grid-item',
                                                   'id': 'idpais',
                                                   'onchange':
                                                   'changecountry()'
                                               }))
    ciudad = forms.CharField(label="ciudad",
                             required=True,
                             widget=forms.Select(choices=[["init", "init"]],
                                                 attrs={
                                                     'class': 'form-control',
                                                     'id': 'ciudades'
                                                 }))

    fecha_nacimiento = forms.DateField(label="Fecha de nacimiento",
                                       required=False,
                                       widget=forms.SelectDateWidget(
                                           attrs={'class': 'form-control'},
                                           months=months,
                                           years=years,
                                           empty_label=("Año", "Mes", "Día"),
                                       ))  #campo opcional
    email = forms.EmailField(
        label="Email",
        required=True,
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': 'Escribe tu email'
        }),
        max_length=100,
        min_length=3)  #campo opcional

    genero = forms.CharField(label="Generos",
                             required=False,
                             widget=forms.Select(
                                 attrs={'class': 'form-control'},
                                 choices=GENEROS))

    contraseña = forms.CharField(
        label="Contraseña",
        required=True,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': 'Escribe tu contraseña'
        }))

    confirmacion = forms.BooleanField(widget=forms.CheckboxInput())

    captcha = ReCaptchaField(
        public_key='6LdaUqcUAAAAAOK3xzjo-oknTM33fbXExlcwFG0z',
        private_key='6LdaUqcUAAAAANtBkskWrDSPz2SezQT_i3jsSRon',
        widget=ReCaptchaV2Checkbox())

    def clean_nombres(self):
        nombres = self.cleaned_data['nombres']
        if not nombres.isalpha():
            raise forms.ValidationError('Introduce un nombre valido')
        return nombres

    def clean_apellidos(self):
        apellidos = self.cleaned_data['apellidos']
        if not apellidos.isalpha():
            raise forms.ValidationError('Introduce un apellido valido')
        return apellidos

    def clean_email(self):
        email = self.cleaned_data['email']
        if not email.endswith('@utp.edu.co'):
            raise forms.ValidationError('El email debe ser @utp.edu.co')
        else:
            if Egresado.objects.filter(email=email).exists():
                raise forms.ValidationError(
                    'El email ya esta registrado, prueba con otro')
        return email

    def clean_contraseña(self):
        contraseña = self.cleaned_data['contraseña']
        print(contraseña.isdigit())
        if contraseña.isdigit():
            raise forms.ValidationError(
                'Su contraseña no puede ser completamente numérica')
        elif len(contraseña) < 8:
            raise forms.ValidationError(
                'Su contraseña debe tener al menos 8 caracteres')
        return contraseña

    def clean_DNI(self):
        IDENTIFICACION = ["Cédula de ciudadania", "Pasaporte"]
        dni = self.cleaned_data['DNI']
        Tipo_de_identificacion = self.cleaned_data['Tipo_de_identificacion']
        if Tipo_de_identificacion == IDENTIFICACION[1]:
            if not dni[0:3].isalpha() or not dni[3:6].isdigit():
                raise forms.ValidationError("DNI invalido")
        elif Tipo_de_identificacion == IDENTIFICACION[0]:
            if len(dni) < 8 or len(dni) > 10:
                raise forms.ValidationError("DNI debe tener de 8 a 10 digitos")
            elif not dni.isdigit():
                raise forms.ValidationError(
                    "DNI solo debe contener numeros del 0-9")
        return dni

    def clean_fecha_nacimiento(self):
        date_born = self.cleaned_data['fecha_nacimiento']
        if not date_born:
            raise forms.ValidationError("Ingrese una fecha válida")
        return date_born

    def clean_confirmacion(self):
        confirmar = self.cleaned_data['confirmacion']
        if not confirmar:
            raise forms.ValidationError("Confirme antes de continuar")
        return confirmar