class RegistrationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password.""" password_1 = forms.CharField(widget=forms.PasswordInput, label=_('Password 1')) password_2 = forms.CharField(widget=forms.PasswordInput, label=_('Password 2')) if settings.CAPTCHA_TYPE == 'simple_math': question_template = _('What is %(num1)i %(operator)s %(num2)i? ') are_you_a_robot = MathCaptchaField(label=_('Answer this question: ')) elif settings.CAPTCHA_TYPE == 'recaptcha': are_you_a_robot = ReCaptchaField(widget=ReCaptchaWidget()) else: are_you_a_robot = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = models.Account fields = ( 'email', 'salutation', 'first_name', 'middle_name', 'last_name', 'department', 'institution', 'country', ) def clean_password_2(self): password_1 = self.cleaned_data.get("password_1") password_2 = self.cleaned_data.get("password_2") if password_1 and password_2 and password_1 != password_2: raise forms.ValidationError( 'Your passwords do not match.', code='password_mismatch', ) if not len(password_2) >= 12: raise forms.ValidationError( 'Your password is too short, it should be 12 characters or greater in length.', code='password_to_short', ) return password_2 def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.username = self.cleaned_data['email'] user.set_password(self.cleaned_data["password_1"]) user.is_active = False user.confirmation_code = uuid.uuid4() user.email_sent = timezone.now() user.save() if commit: user.save() return user
class ContactUsForm(forms.Form): name = forms.CharField(label='Your name*', required=True) email = forms.EmailField(label='Your email*', required=True) feedback_type = forms.ChoiceField(label='Feedback on*', required=True, choices=ContactFeedbackType.CHOICES) comments = forms.CharField( label='Comments*', required=True, widget=forms.Textarea) contact_number = forms.CharField( label='Your contact number', required=False) captcha = MathCaptchaField() def clean_contact_number(self): contact_number = self.cleaned_data['contact_number'] error_message = [] if not contact_number.isdigit(): error_message.append( "Contact Number should only consist digits") if not len(contact_number) == 10: error_message.append( "Contact Number should be of 10 digits") if error_message: raise ValidationError(error_message) return contact_number
class EntryForm(forms.ModelForm): rules = forms.BooleanField( error_messages={'required': 'You must agree to the Rules to submit.'}) captcha = MathCaptchaField(required=True) # custom validatons def clean_screenshot(self): screenshot = self.cleaned_data.get('screenshot', False) if screenshot: if screenshot._size > 20 * 1024 * 1024: raise ValidationError( "Image file is too large, max. 20MB allowed.") return screenshot def clean_file(self): file = self.cleaned_data.get('file', False) if file: if file._size > 20 * 1024 * 1024: raise ValidationError("File is too large, max. 20MB allowed.") return file class Meta: model = Entry fields = ('name', 'email', 'description', 'screenshot', 'file', 'url', 'rules')
class RegistrationForm(UserCreationForm): captcha = MathCaptchaField() email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'captcha', 'password1', 'password2']
class SignUpForm(UserCreationForm): password1 = forms.CharField(max_length=16, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Password', 'id': "nameValidation1" })) password2 = forms.CharField(max_length=16, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Confirm Password', 'id': "nameValidation2" })) captcha = MathCaptchaField() class Meta: model = User fields = ( 'username', 'password1', 'password2', ) widgets = { 'username': TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Username', 'id': 'username', "onchange": "UsernameValidate()" }), }
class UserRegisterForm(UserCreationForm): email = forms.EmailField() captcha2 = MathCaptchaField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2']
class ContactForm(forms.ModelForm): if settings.CAPTCHA_TYPE == 'simple_math': question_template = _('What is %(num1)i %(operator)s %(num2)i? ') are_you_a_robot = MathCaptchaField(label=_('Answer this question: ')) elif settings.CAPTCHA_TYPE == 'recaptcha': are_you_a_robot = ReCaptchaField(widget=ReCaptchaWidget()) else: are_you_a_robot = forms.CharField(widget=forms.HiddenInput(), required=False) def __init__(self, *args, **kwargs): subject = kwargs.pop('subject', None) contacts = kwargs.pop('contacts', None) super(ContactForm, self).__init__(*args, **kwargs) if subject: self.fields['subject'].initial = subject if contacts: contact_choices = [] for contact in contacts: contact_choices.append([ contact.email, '{name}, {role}'.format(name=contact.name, role=contact.role) ]) self.fields['recipient'].widget = forms.Select( choices=contact_choices) class Meta: model = core_models.Contact fields = ('recipient', 'sender', 'subject', 'body')
class FormContact(forms.Form): nome = forms.CharField(label='Nome', max_length=80) email = forms.EmailField(label='email', required=True) telefone = forms.CharField(label='Telefone', required=False) assunto = forms.CharField(label='Assunto', max_length=80) mensagem = forms.CharField(label='Mensagem', widget=forms.Textarea()) captcha = MathCaptchaField(widget=MathCaptchaWidget( question_tmpl="Quanto é: %(num1)i %(operator)s %(num2)i?", ))
class SignUpForm(UserCreationForm): captcha = MathCaptchaField() class Meta: model = User fields = ( 'username', 'password1', 'password2', )
class OuvidoriaForm(forms.Form): nome = forms.CharField(label='nome', max_length=80) email = forms.EmailField(label='email', required=True, max_length=80) secretaria = forms.ChoiceField(label='secretaria', widget=forms.Select, choices=SECRETARIA_CHOICES) assunto = forms.ChoiceField(label='assunto', widget=forms.Select, choices=MANIFESTACOES_CHOICES) mensagem = forms.CharField(label='mensagem', widget=forms.Textarea()) captcha = MathCaptchaField()
class FormContact(forms.Form): nome = forms.CharField(label='Nome', max_length=80) sobrenome = forms.CharField(label='Sobrenome', max_length=80) email = forms.EmailField(label='email', required=True) telefone = forms.EmailField(label='Telefone', required=False) secretaria = forms.ChoiceField(label='Secretaria', widget=forms.Select, choices=SECRETARIA_CHOICES) assunto = forms.CharField(label='Assunto', max_length=80) mensagem = forms.CharField(label='Mensagem', widget=forms.Textarea()) captcha = MathCaptchaField(widget=MathCaptchaWidget( question_tmpl="Quanto é: %(num1)i %(operator)s %(num2)i?", ))
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if settings.CAPTCHA_TYPE == 'simple_math': question_template = _('What is %(num1)i %(operator)s %(num2)i? ') are_you_a_robot = MathCaptchaField( label=_('Answer this question: ')) elif settings.CAPTCHA_TYPE == 'recaptcha': are_you_a_robot = ReCaptchaField(widget=ReCaptchaWidget()) else: are_you_a_robot = forms.CharField(widget=forms.HiddenInput(), required=False) self.fields["are_you_a_robot"] = are_you_a_robot
class ContactForm(forms.Form): """Contact form to send an email to the site admin.""" name = forms.CharField(max_length=100, required=False) email = forms.CharField(max_length=254, required=False) message = forms.CharField(widget=forms.Textarea(attrs={ 'rows': 20, 'cols': 20 })) captcha_errors = { 'invalid': 'Please check your maths', 'invalid_number': 'Please enter numerals' } captcha = MathCaptchaField(error_messages=captcha_errors)
def captcha_field(self): if settings.CAPTCHA_TYPE == 'simple_math': self.question_template = _( 'What is %(num1)i %(operator)s %(num2)i? ') return MathCaptchaField(label=_('Anti-spam captcha')) elif settings.CAPTCHA_TYPE == 'recaptcha': field = ReCaptchaField(widget=ReCaptchaWidget()) field.label = "Anti-spam captcha" return field else: logger.warning("Unknown CAPTCHA_TYPE in settings: %s" "" % settings.CAPTCHA_TYPE) return self.no_cacptcha_field
class ContactForm(forms.ModelForm): question_template = _('What is %(num1)i %(operator)s %(num2)i? ') are_you_a_robot = MathCaptchaField(label=_('Answer this question: ')) def __init__(self, *args, **kwargs): subject = kwargs.pop('subject', None) super(ContactForm, self).__init__(*args, **kwargs) self.fields['are_you_a_robot'].required = True if subject: self.fields['subject'].initial = subject class Meta: model = core_models.Contact fields = ('recipient', 'sender', 'subject', 'body')
class OuvidoriaForm(forms.Form): nome = forms.CharField(label='*Nome', max_length=80) sobrenome = forms.CharField(label='*Sobrenome', max_length=80) email = forms.EmailField(label='email', required=False, max_length=80) telefone = forms.CharField(label='*Telefone para contato', max_length=11) secretaria = forms.ChoiceField( label='*Órgão para o qual você quer enviar sua manifestação', widget=forms.Select, choices=SECRETARIA_CHOICES) assunto = forms.ChoiceField(label='*Sobre qual assunto você quer falar ', widget=forms.Select, choices=MANIFESTACOES_CHOICES) mensagem = forms.CharField( label='*Descreva abaixo o conteúdo de sua manifestação.', widget=forms.Textarea()) captcha = MathCaptchaField(widget=MathCaptchaWidget( question_tmpl="*Quanto é: %(num1)i %(operator)s %(num2)i?", ))
class UserCreationForm(forms.ModelForm): password1 = forms.CharField( label='Password', widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Password' })) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'confirm password' })) captcha = MathCaptchaField() class Meta: model = MyUser fields = ('email', 'date_of_birth') def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['date_of_birth'].widget.attrs = { 'class': 'form-control', 'placeholder': 'Date of birth' } self.fields['email'].widget.attrs = { 'class': 'form-control', 'placeholder': 'Email' } def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
class ContactForm(forms.ModelForm): if settings.CAPTCHA_TYPE == 'simple_math': question_template = _('What is %(num1)i %(operator)s %(num2)i? ') are_you_a_robot = MathCaptchaField(label=_('Answer this question: ')) elif settings.CAPTCHA_TYPE == 'recaptcha': are_you_a_robot = ReCaptchaField(widget=ReCaptchaWidget()) else: are_you_a_robot = forms.CharField(widget=forms.HiddenInput(), required=False) def __init__(self, *args, **kwargs): subject = kwargs.pop('subject', None) super(ContactForm, self).__init__(*args, **kwargs) if subject: self.fields['subject'].initial = subject class Meta: model = core_models.Contact fields = ('recipient', 'sender', 'subject', 'body')
class PartnerForm(forms.Form): partner_choices = ( ('profit', 'Profit making'), ('non-profit', "Non Profit")) org_name = forms.CharField(label='Organization Name*', required=True) org_url = forms.URLField(label='Organization Url*', required=True) partner_type = forms.ChoiceField( label='Type of organization*', required=True, choices=partner_choices) description = forms.CharField( label='Describe how your organization will help both of us *', required=True, widget=forms.Textarea) python_use = forms.CharField( label='Use of python in your organization ? *', required=True, widget=forms.Textarea) name = forms.CharField(label='Your Name*', required=True) email = forms.EmailField(label='Your email*', required=True) contact_number = forms.CharField( label='Your contact number', required=True) comments = forms.CharField( label='Comments*', required=True, widget=forms.Textarea) captcha = MathCaptchaField() def clean_contact_number(self): contact_number = self.cleaned_data['contact_number'] error_message = [] if not contact_number.isdigit(): error_message.append( "Contact Number should only consist digits") if not len(contact_number) == 10: error_message.append( "Contact Number should be of 10 digits") if error_message: raise ValidationError(error_message) return contact_number
class CommentForm(UserCommentForm): user_name = forms.CharField(label=_('Username'), initial=_('anonymous')) user_email = forms.EmailField(label=_('E-mail'), required=False) captcha = MathCaptchaField(required=True, error_messages={'invalid': _('Welcome robot')}) class Meta: model = Comment fields = ("user_name", "user_email", "bodytext") if MAX_LENGTH_TEXTAREA is not None: widgets = { 'bodytext': forms.Textarea(attrs={'maxlength': MAX_LENGTH_TEXTAREA}) } def clean_user_name(self): self.error_msg user_name = self.cleaned_data.get('user_name') if user_name: if not user_name.strip(): raise forms.ValidationError(self.error_msg) return user_name
def test_instantiation_with_values(self, mocked): MathCaptchaField(start_int=5, end_int=10) mocked.assert_called_once_with(start_int=5, end_int=10)
def __init__(self, contactFormInstance, request, *args, **kwargs): super(ContactFormPlus, self).__init__(*args, **kwargs) if 'instance' not in kwargs: for extraField in contactFormInstance.extrafield_set.all(): if extraField.fieldType == 'CharField': self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, initial=extraField.initial, required=extraField.required) elif extraField.fieldType == 'BooleanField': self.fields[slugify(extraField.label)] = forms.BooleanField(label=extraField.label, initial=extraField.initial, required=extraField.required) elif extraField.fieldType == 'EmailField': self.fields[slugify(extraField.label)] = forms.EmailField(label=extraField.label, initial=extraField.initial, required=extraField.required) elif extraField.fieldType == 'DecimalField': self.fields[slugify(extraField.label)] = forms.DecimalField(label=extraField.label, initial=extraField.initial, required=extraField.required) elif extraField.fieldType == 'FloatField': self.fields[slugify(extraField.label)] = forms.FloatField(label=extraField.label, initial=extraField.initial, required=extraField.required) elif extraField.fieldType == 'FileField': self.fields[slugify(extraField.label)] = forms.FileField(label=extraField.label, initial=extraField.initial, required=extraField.required) elif extraField.fieldType == 'ImageField': self.fields[slugify(extraField.label)] = forms.ImageField(label=extraField.label, initial=extraField.initial, required=extraField.required) elif extraField.fieldType == 'IntegerField': self.fields[slugify(extraField.label)] = forms.IntegerField(label=extraField.label, initial=extraField.initial, required=extraField.required) elif extraField.fieldType == 'IPAddressField': self.fields[slugify(extraField.label)] = forms.IPAddressField(label=extraField.label, initial=extraField.initial, required=extraField.required) elif extraField.fieldType == 'auto_Textarea': self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, initial=extraField.initial, widget=forms.Textarea, required=extraField.required) elif extraField.fieldType == 'auto_hidden_input': self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, initial=extraField.initial, widget=forms.HiddenInput, required=False) elif extraField.fieldType == 'auto_referral_page': lInitial = _("No referral available.") if request: lInitial = request.META.get('HTTP_REFERER', _('No referral available.')) self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, initial=lInitial, # NOTE: This overwrites extraField.initial! widget=forms.HiddenInput, required=False) elif extraField.fieldType == 'MathCaptcha': self.fields[slugify(extraField.label)] = MathCaptchaField( label=extraField.label, initial=extraField.initial, required=True) elif extraField.fieldType == 'ReCaptcha': self.fields[slugify(extraField.label)] = ReCaptchaField( label=extraField.label, initial=extraField.initial, required=True) elif extraField.fieldType == 'auto_GET_parameter': lInitial = _("Key/value parameter not available.") if request: lInitial = request.GET.get(slugify(extraField.label), 'n/a') self.fields[slugify(extraField.label)] = forms.CharField(label=extraField.label, initial=lInitial, # NOTE: This overwrites extraField.initial! widget=forms.HiddenInput, required=False) elif extraField.fieldType == 'CharFieldWithValidator': self.fields[slugify(extraField.label)] = forms.CharField( label=extraField.label, initial=extraField.initial, required=extraField.required, validators=get_validators())
class F(forms.Form): captcha = MathCaptchaField()
def test_compress(self): f = MathCaptchaField() with mock.patch('simplemathcaptcha.fields.hash_answer') as mocked: mocked.return_value = 'hashed_answer' result = f.compress(['abc', 'hashed_answer']) self.assertIsNone(result)
class RegisterForm(forms.Form): """Form used for to register new users.""" email = forms.EmailField(label=u'Adresse email') username = forms.CharField(label=u'Nom d’utilisateur', max_length=30) password = forms.CharField(label=u'Mot de passe', max_length=76, widget=forms.PasswordInput) password_confirm = forms.CharField(label=u'Confirmation', max_length=76, widget=forms.PasswordInput) captcha = MathCaptchaField(error_messages={ 'invalid': u'Vérifiez votre réponse et réessayez.', 'invalid_number': u'Entrez un nombre entier.', }, widget=MathCaptchaWidget( question_tmpl=u'Quel est le résultat de ' u'%(num1)i %(operator)s %(num2)i ?', question_class='captcha')) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout( Fieldset( u'Identifiants', Field('username'), Field('password'), Field('password_confirm'), Field('email'), ), Fieldset( u'Captcha', Field('captcha'), ), Div(Submit('submit', u'Valider mon inscription'), HTML(u'<a href="/" class="button secondary">Annuler</a>'), css_class='button-group')) super().__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() password = cleaned_data.get('password') password_confirm = cleaned_data.get('password_confirm') # Check that the password and its confirmation match if not password_confirm == password: msg = u'Les mots de passe sont différents.' self.add_error('password', msg) self.add_error('password_confirm', msg) # Remove the wrong passwords from the form if 'password' in cleaned_data: del cleaned_data['password'] if 'password_confirm' in cleaned_data: del cleaned_data['password_confirm'] # Check that the user doesn't exist yet username = cleaned_data.get('username') if User.objects.filter(username=username).count() > 0: msg = u'Ce nom d’utilisateur est déjà utilisé.' self.add_error('username', msg) return cleaned_data
def test_compress_with_wrong_answer(self): f = MathCaptchaField() with mock.patch('simplemathcaptcha.fields.hash_answer') as mocked: mocked.return_value = 'bad_hashed_answer' with self.assertRaises(ValidationError): f.compress(['abc', 'hashed_answer'])
def test_compress_with_nothing(self): f = MathCaptchaField() result = f.compress([]) self.assertIsNone(result)
def test_instantiation_with_widget_and_values_is_error(self): with self.assertRaises(TypeError): MathCaptchaField(start_int=5, end_int=10, widget=MathCaptchaWidget())
class UserRegisterForm(UserCreationForm): captcha = MathCaptchaField() class Meta: model = User fields = ['username', 'password1', 'password2', 'captcha']
def test_instantiation_with_widget(self, mocked): MathCaptchaField(widget=MathCaptchaWidget()) self.assertEqual(mocked.call_count, 0)