Ejemplo n.º 1
0
def test_clean_captcha(no_recaptcha):  # pylint: disable=redefined-outer-name
    """
    This example shows how to override the captach for testing purposes used below. The datadict
    passed to the form and subsquently the widget must contatin the g-recaptcha-response with a
    value of passed, and there must ben an environment variable NORECAPTCHA_TESTING set to 'True' to
    by pass the captcha when the form is cleaned.
    """
    field = NoReCaptchaField()
    value = field.widget.value_from_datadict(
        {
            "g-recaptcha-response": "PASSED",
        }, {}, {})
    field.clean(value)
Ejemplo n.º 2
0
 def __init__(self, *args, **kwargs):
     super(SignUpForm, self).__init__(*args, **kwargs)
     self.request = kwargs.pop('request', None)
     self.fields['captcha'] = NoReCaptchaField()
     self.fields['email'] = forms.EmailField(
         label=_('Email'), required=True,
         widget=forms.EmailInput(attrs={'placeholder': _('Email')}))
Ejemplo n.º 3
0
class CreateUserForm(forms.ModelForm):

    email = forms.EmailField(max_length=254, required=True)
    password = forms.CharField(max_length=128,
                               label='Password',
                               widget=widgets.PasswordInput)
    password2 = forms.CharField(max_length=128,
                                label='Password Confirmation',
                                widget=widgets.PasswordInput)

    captcha = NoReCaptchaField(
        gtag_attrs={
            'callback':
            'onCaptchaSubmit',  # name of JavaScript callback function
            'bind': 'btn_submit'  # submit button's ID in the form template
        },
        widget=InvisibleReCaptchaWidget)

    def clean_password2(self):
        if self.cleaned_data['password2'] == self.cleaned_data['password']:
            return self.cleaned_data['password2']
        raise ValidationError("The passwords do not match")

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'password', 'password2', 'captcha']

    pass
Ejemplo n.º 4
0
class CustomSignupForm(forms.Form):

    captcha = NoReCaptchaField(label='')

    def signup(self, request, user):
        """ Required, or else it throws deprecation warnings """
        pass
Ejemplo n.º 5
0
class MyAdminLoginForm(AuthenticationForm):
    captcha = NoReCaptchaField(
        gtag_attrs={
            'callback': 'onSubmit',  # name of JavaScript callback function
            'bind': 'submit-button'  # submit button's ID in the form template
        },
        widget=InvisibleReCaptchaWidget)
Ejemplo n.º 6
0
class SignupForm(forms.Form):
    if hasattr(settings, 'NORECAPTCHA_SITE_KEY') and\
       hasattr(settings, 'NORECAPTCHA_SECRET_KEY'):
        captcha = NoReCaptchaField()

    def signup(self, request, user):
        pass
Ejemplo n.º 7
0
class TicketForm(ModelForm):
    captcha = NoReCaptchaField()

    class Meta:
        model = Ticket
        fields = ['title', 'content']

        widgets = {
            'title': TextInput(attrs={'placeHolder': 'Başlık'}),
            'content': Textarea(attrs={'placeHolder': 'İçerik', 'style': 'width:100% !important;'}),
        }

    def save(self, user=None, commit=True):
        instance = super(TicketForm, self).save(commit=False)
        instance.user = user
        if commit:
            instance.save()
        return instance

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

    def clean(self):
        cleaned_data = super(TicketForm, self).clean()
        if Ticket.objects.filter(user=self.request.user).count() >= 5:
            raise ValidationError("Bir kullanıcı 5'den fazla soru soramaz.")
        return cleaned_data
Ejemplo n.º 8
0
class AppForm(forms.Form):
    #    gens = forms.ChoiceField(choices=GENTES_CHOICES, required=True, label='Gens (This is the familial clan with which every natural born Roman citizen was associated and would be the basis for the name by which most people addressed them.')
    #    gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.RadioSelect, required=True, label='Gender')
    #    praenomen = forms.ChoiceField(choices=PRAENOMINA_CHOICES, required=True, label='Praenomen (This is the name by which very close friends and familiy members would address you.')
    # Trying out stat generation
    #   It won't regenerate the numbers on page refresh this way
    #    dict_attributes = {'str':8, 'dex':8, 'con':8, 'int':8, 'wis':8, 'cha':8}
    #    points = 27
    #    while points > 0:
    #        attribute = random.choice(list(dict_attributes))
    #        value = dict_attributes[attribute]
    #        if value <= 14:
    #            if points > 0:
    #                if value < 13:
    #                    dict_attributes[attribute] += 1
    #                    points -= 1
    #                elif value == 13 or value == 14:
    #                    if points >= 2:
    #                        dict_attributes[attribute] += 1
    #                        points -= 2
    #    strength = dict_attributes['str'] + 1
    #    dexterity = dict_attributes['dex'] + 1
    #    constitution = dict_attributes['con'] + 1
    #    intelligence = dict_attributes['int'] + 1
    #    wisdom = dict_attributes['wis'] + 1
    #    charisma = dict_attributes['cha'] + 1
    #    stuff = (f"Vires: {strength} Celeritas: {dexterity} Valetudo: {constitution} Mens: {intelligence} Sapientia: {wisdom} Amicitia: {charisma}")
    # Changed up to the comment above

    captcha = NoReCaptchaField()
Ejemplo n.º 9
0
class MessageForm(forms.ModelForm):
    name = forms.CharField(
        max_length=70,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": "Name"
        }),
    )
    email = forms.EmailField(widget=forms.TextInput(attrs={
        "class": "form-control",
        "placeholder": "Email"
    }))
    captcha = NoReCaptchaField(
        error_messages={"required": "This check is mandatory."})

    class Meta:
        model = Message
        fields = ["name", "message", "email"]
        widgets = {
            "message":
            forms.Textarea(attrs={
                "class": "form-control",
                "placeholder": "Message"
            }),
        }
Ejemplo n.º 10
0
class RegisterForm(ModelForm):
    """Form for registration page"""
    captcha = NoReCaptchaField()
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'password')
        widgets = {'password': PasswordInput()}
Ejemplo n.º 11
0
class ChangePassForm(forms.Form):
    password1 = forms.CharField(required=True,
                                label="",
                                max_length=50,
                                min_length=6,
                                widget=forms.PasswordInput(
                                    attrs={
                                        'placeholder': 'choose a password',
                                        'class': 'form-control input-perso',
                                        'id': 'password_input1'
                                    }))
    newpassword1 = forms.CharField(required=True,
                                   label="",
                                   max_length=50,
                                   min_length=6,
                                   widget=forms.PasswordInput(
                                       attrs={
                                           'placeholder': 'choose a password',
                                           'class': 'form-control input-perso',
                                           'id': 'password_input2'
                                       }))
    newpassword2 = forms.CharField(required=True,
                                   label="",
                                   max_length=50,
                                   min_length=6,
                                   widget=forms.PasswordInput(
                                       attrs={
                                           'placeholder': 'choose a password',
                                           'class': 'form-control input-perso',
                                           'id': 'password_input3'
                                       }))
    captcha = NoReCaptchaField()
Ejemplo n.º 12
0
class SignupForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    email = forms.EmailField(
        error_messages={
            'unique':
            pgettext_lazy('Registration error',
                          'This email has already been registered.')
        })
    captcha = NoReCaptchaField()

    class Meta:
        model = User
        fields = ('email', )
        labels = {
            'email': pgettext_lazy('Email', 'Email'),
            'password': pgettext_lazy('Password', 'Password')
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self._meta.model.USERNAME_FIELD in self.fields:
            self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update(
                {'autofocus': ''})

    def save(self, request=None, commit=True):
        user = super().save(commit=False)
        password = self.cleaned_data['password']
        user.set_password(password)
        if commit:
            user.save()
        return user
Ejemplo n.º 13
0
class CouponActivateForm(forms.Form):
    captcha = NoReCaptchaField()
    code = forms.CharField(max_length=20)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(CouponActivateForm, self).__init__(*args, **kwargs)
        # set classes
        for k, v in self.fields.items():
            v.widget.attrs['class'] = FIELD_CLASSES.get(k)
            v.widget.icon = FIELD_ICONS.get(k)

    def clean(self):
        cleaned_data = super(CouponActivateForm, self).clean()
        # raise the error if the captcha is bad before passing through
        if self._errors:
            # small hack here as the error would duplicate otherwise
            errors = self._errors.copy()
            self.__dict__['_errors'] = {}
            raise ValidationError(errors)
        try:
            coupon = Coupon.objects.get(code=cleaned_data.get('code'),
                                        activated=False)
            coupon.activated = True
            coupon.activated_by = self.user
            self.user.end_date = self.user.end_date + relativedelta(
                months=coupon.months)
            coupon.save()
            self.user.save()
        except Coupon.DoesNotExist:
            raise ValidationError({'code': 'Incorrect code'})
Ejemplo n.º 14
0
class sellUrlForm(forms.Form):
    sellUrl = forms.URLField(
        required=True,
        error_messages={'invalid': ("Invalid Url")},
        validators=[URLValidator],
        widget=forms.TextInput(attrs={
            'id': 'sell_url_input',
            'placeholder': "your domain's url"
        }))
    tag1 = forms.CharField(
        required=False,
        label="",
        widget=forms.TextInput(attrs={
            'id': 'tag',
            'placeholder': 'tag1',
            'class': 'form-control'
        }),
        max_length=30,
        min_length=3)
    tag2 = forms.CharField(required=False,
                           label="",
                           widget=forms.TextInput(
                               attrs={
                                   'id': 'tag',
                                   'placeholder': 'tag2',
                                   'class': 'form-control input-perso'
                               }),
                           max_length=30,
                           min_length=3)
    tag3 = forms.CharField(required=False,
                           label="",
                           widget=forms.TextInput(
                               attrs={
                                   'id': 'tag',
                                   'placeholder': 'tag3',
                                   'class': 'form-control input-perso'
                               }),
                           max_length=30,
                           min_length=3)
    tag4 = forms.CharField(required=False,
                           label="",
                           widget=forms.TextInput(
                               attrs={
                                   'id': 'tag',
                                   'placeholder': 'tag4',
                                   'class': 'form-control input-perso'
                               }),
                           max_length=30,
                           min_length=3)
    tag5 = forms.CharField(required=False,
                           label="",
                           widget=forms.TextInput(
                               attrs={
                                   'id': 'tag',
                                   'placeholder': 'tag5',
                                   'class': 'form-control input-perso'
                               }),
                           max_length=30,
                           min_length=3)
    captcha = NoReCaptchaField()
Ejemplo n.º 15
0
class TicketCommentForm(ModelForm):
    captcha = NoReCaptchaField()

    class Meta:
        model = TicketComment
        fields = ['comment']

        widgets = {
            'comment': Textarea(attrs={'placeHolder': 'Yorum yap', 'style': 'width:100% !important;'}),
        }

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

    def save(self, user=None, ticket=None, commit=True):
        instance = super(TicketCommentForm, self).save(commit=False)
        instance.user = user
        instance.ticket = ticket
        if commit:
            instance.save()
        return instance

    def clean(self):
        cleaned_data = super(TicketCommentForm, self).clean()
        comment_count = TicketComment.objects.filter(ticket=self.ticket).count()
        if not self.ticket.ticket_status:
            raise ValidationError("Bu soru moderatör tarafından kapatıldığı için yorum yapamazsınız.")
        elif comment_count == 0:
            raise ValidationError("Cevap verilmeyen bir soruya yorum yapamazsınız. "
                                  "Lütfen moderatörün cevap vermesini bekleyin.")
        elif comment_count >= 5:
            raise ValidationError("Bir soruya 5'dan fazla yorum eklenemez.")
        return cleaned_data
Ejemplo n.º 16
0
class DocumentForm(ModelForm):
    captcha = NoReCaptchaField()

    class Meta:
        model = TrainingDocument
        fields = ['name', 'document_url']

        widgets = {
            'name': TextInput(attrs={'placeHolder': 'Döküman adı'}),
            'document_url': URLInput(attrs={'placeHolder': 'Döküman URLi'})
        }

    def save(self, training=None, commit=True):
        instance = super(DocumentForm, self).save(commit=False)
        instance.training = training
        if commit:
            instance.save()
        return instance

    def clean(self):
        cleaned_data = super(DocumentForm, self).clean()
        training_count = TrainingDocument.objects.filter(training=self.training).count()
        if training_count >= 10:
            raise ValidationError('Bir eğitime en fazla 10 döküman eklenebilir.')
        return cleaned_data

    def __init__(self, *args, **kwargs):
        self.training = kwargs.pop('training')
        super(DocumentForm, self).__init__(*args, **kwargs)
Ejemplo n.º 17
0
class ContactForm(forms.Form):
    cst = {'class': 'form-control cst__radius', 'required': 'required'}

    email = forms.EmailField(required=True, widget=forms.TextInput(attrs=cst))
    subject = forms.CharField(required=True, widget=forms.TextInput(attrs=cst))
    message = forms.CharField(required=True, widget=forms.Textarea(attrs=cst))

    captcha = NoReCaptchaField()
Ejemplo n.º 18
0
class AnonymousUserBillingForm(forms.Form):
    """Additional billing information form for users who are not logged in."""

    email = forms.EmailField(
        required=True, widget=forms.EmailInput(
            attrs={'autocomplete': 'billing email'}),
        label=pgettext_lazy('Billing form field label', 'Email'))
    captcha = NoReCaptchaField()
Ejemplo n.º 19
0
class CommentForm(forms.ModelForm):
    class Meta:
        """ created, author, body, post """
        model = Comment
        widgets = {'aproved': forms.HiddenInput()}
        exclude = ["post"]

    captcha = NoReCaptchaField()
Ejemplo n.º 20
0
class RegistrationForm(_RegistrationForm):
    name = forms.CharField()
    surname = forms.CharField()
    phone = forms.CharField(required=False)
    organization = forms.ModelChoiceField(queryset=Organization.objects.all(),
                                          required=False,
                                          label=_("Organization"))
    recaptcha = NoReCaptchaField()
Ejemplo n.º 21
0
class UserCreateForm(UserCreationForm):
    SEX_OPTIONS = (
        ('M', _('Man')),
        ('W', _('Woman')),
        ('N', _('Non-binary')),
    )
    aux = _("Format: dd/mm/YYYY"),

    first_name = forms.CharField(label=_('First name'), required=False)
    last_name = forms.CharField(label=_('Last name'), required=False)
    email = forms.EmailField(label=_('Email'), required=True)
    birthdate = forms.DateTimeField(label=_('Birthdate'),
                                    input_formats=['%d/%m/%Y'],
                                    help_text=aux,
                                    required=False)
    city = forms.CharField(label=_('City'), required=True)
    sex = forms.ChoiceField(label=_('Sex'),
                            choices=SEX_OPTIONS,
                            required=False)
    captcha = NoReCaptchaField()

    class Meta:
        model = User
        fields = ("first_name", "last_name", "email", "birthdate", "city",
                  "sex", "password1", "password2", "captcha")

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.first_name = self.cleaned_data["first_name"]
        user.last_name = self.cleaned_data["last_name"]
        user.email = self.cleaned_data["email"]
        user.birthdate = self.cleaned_data["birthdate"]
        user.city = self.cleaned_data["city"]
        user.sex = self.cleaned_data["sex"]

        if commit:
            user.save()
        return user

    #  Validations

    def clean(self, *args, **kwargs):
        cleaned_data = super(UserCreateForm, self).clean(*args, **kwargs)
        email = cleaned_data.get('email', None)
        if email is not None:  # look for in db
            users = User.objects.all()

            for u in users:
                if email == u.email:
                    self.add_error('email', _('Email alredy exits'))
                    break

        birthdate = cleaned_data.get('birthdate', None)
        if birthdate is not None:
            now = timezone.now()

            if birthdate > now:
                self.add_error('birthdate', _('Future date not posible'))
Ejemplo n.º 22
0
class SignupForm(forms.Form):
    first_name = forms.CharField(
        widget=forms.TextInput(attrs={
            'id': 'first_name',
            'class': 'form-control floating-label'
        }),
        required=True)

    last_name = forms.CharField(
        widget=forms.TextInput(attrs={
            'id': 'last_name',
            'class': 'form-control floating-label'
        }),
        required=True)

    email = forms.CharField(
        widget=forms.EmailInput(attrs={
            'id': 'email',
            'class': 'form-control floating-label'
        }),
        required=True)

    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'id': 'password',
            'class': 'form-control floating-label'
        }),
        required=True)

    company_name = forms.CharField(
        widget=forms.TextInput(attrs={
            'id': 'company_name',
            'class': 'form-control floating-label'
        }), )
    company_url = forms.CharField(
        widget=forms.URLInput(attrs={
            'id': 'company_url',
            'class': 'form-control floating-label'
        }),
        required=False)
    company_logo = forms.ImageField(
        widget=forms.FileInput(attrs={
            'id': 'company_logo',
            'class': 'form-control floating-label'
        }),
        required=True)

    captcha = NoReCaptchaField()

    def clean(self):
        cleaned_data = super(SignupForm, self).clean()
        email = cleaned_data.get("email")
        users_count = User.objects.filter(username=email).count()
        if users_count > 0:
            raise forms.ValidationError(
                _('The email already is already in use.',
                  params={'value': '42'}))
        return self.cleaned_data
Ejemplo n.º 23
0
 def Create_Fields(self):
     self.fields['title'] = forms.CharField(max_length=100,
                                            initial=Text(self, 83))
     self.fields['client'] = forms.CharField(max_length=50)
     self.fields['email'] = forms.EmailField(max_length=50)
     self.fields['product'] = forms.CharField(max_length=50, required=False)
     self.fields['url'] = forms.URLField(required=False)
     self.fields['message'] = forms.CharField(max_length=2000)
     self.fields['captcha'] = NoReCaptchaField()
Ejemplo n.º 24
0
class MessageForm(forms.Form):
    message = forms.CharField(
        label="Write Message",
        max_length=100,
        error_messages={'required': 'Please, enter a message.'})
    if settings.USE_CAPTCHA:
        captcha = NoReCaptchaField(
            label='',
            error_messages={'required': 'Captcha validation is required'})
Ejemplo n.º 25
0
class RegistrationForm(forms.ModelForm):
    error_messages = {
        'duplicate_username': ("此帳號已被使用"),
        'empty_last_name': ("請選擇學校"),
    }

    username = forms.RegexField(label="User name",
                                max_length=30,
                                regex=r"^[\w.@+-]+$",
                                error_messages={'invalid': ("帳號名稱無效")})
    password = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Repeat password',
                                widget=forms.PasswordInput)
    captcha = NoReCaptchaField(label='')

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

    def clean_password2(self):
        cd = self.cleaned_data
        if cd['password'] != cd['password2']:
            raise forms.ValidationError('Passwords don\'t match.')
        return cd['password2']

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields['username'].label = "帳號"
        self.fields['first_name'].label = "暱稱"
        self.fields['email'].label = "電子郵件"
        self.fields['password'].label = "密碼"
        self.fields['password2'].label = "再次確認密碼"

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        if self.instance.username == username:
            return username
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(
            self.error_messages['duplicate_username'],
            code='duplicate_username',
        )

    def clean_last_name(self):
        lastname = self.cleaned_data["last_name"]
        if lastname:
            return lastname
        raise forms.ValidationError(
            self.error_messages['empty_last_name'],
            code='empty_last_name',
        )
Ejemplo n.º 26
0
class RegisterForm(BasicInformationForm):
    optin = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'checkbox'}),
        required=True)
    captcha = NoReCaptchaField()

    class Meta:
        model = UserProfile
        fields = ('photo', 'full_name', 'timezone', 'privacy_photo', 'privacy_full_name', 'optin',
                  'privacy_timezone',)
Ejemplo n.º 27
0
class VoterForm(forms.Form):

    email = forms.EmailField()
    zipcode = USZipCodeField()
    captcha = NoReCaptchaField(gtag_attrs={'data-size': 'compact'})

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

    def ignore_captcha(self):
        del self.fields['captcha']
Ejemplo n.º 28
0
class LogInForm():
    captcha = NoReCaptchaField()

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

    def confirm_login_allowed(self, user):
        if not user.is_active or not user.is_validated:
            raise forms.ValidationError('There was a problem with your login.',
                                        code='invalid_login')
Ejemplo n.º 29
0
class ContactForm(forms.Form):
    contact_name = forms.CharField(required=True)
    contact_email = forms.EmailField(required=True)
    content = forms.CharField(required=True, widget=forms.Textarea)
    captcha = NoReCaptchaField()

    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields['contact_name'].label = "Your name:"
        self.fields['contact_email'].label = "Your email:"
        self.fields['content'].label = "Your message:"
Ejemplo n.º 30
0
class PostForm(forms.ModelForm):
    captcha = NoReCaptchaField()

    class Meta:
        model = Post
        fields = ('title', 'text')
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'text': SummernoteWidget(attrs={'class': 'form-control',
                                            'summernote': {'width': '100%', 'placeholder': 'Texto'}}),

        }