class PostCreate(ModelForm): captcha = ReCaptchaField(widget=ReCaptchaWidget()) class Meta: model = Post fields = ('title', 'text', 'image', 'captcha') labels = { 'title': _('Тема'), 'text': _('Текст'), 'image': _('Изображение'), 'captcha': _('Подтвержение'), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'Создать пост', 'title', 'text', 'image', 'captcha', ), ButtonHolder( Submit('submit', 'Создать пост', css_class='btn btn-default')))
class FormMSDSobjectUpdate(forms.ModelForm): captcha = ReCaptchaField(widget=ReCaptchaWidget()) file = forms.FileField(required=False) ext_whitelist = ['.pdf', '.odt', '.docx', '.doc'] def clean_file(self): dev = None if type(self.cleaned_data['file']) == str: return self.cleaned_data['file'] if self.cleaned_data['file']: name = self.cleaned_data['file'].name ext = os.path.splitext(name)[1] ext = ext.lower() if ext not in self.ext_whitelist: raise forms.ValidationError(_("Not allowed filetype!")) data = self.cleaned_data['file'].read() m = hashlib.md5() m.update(data) new_name = "%s%s" % (m.hexdigest(), ext) new_path = os.path.join(settings.STATIC_CRAWL, "%s%s" % (m.hexdigest(), ext)) with open(new_path, 'wb') as arch: arch.write(data) dev = new_name elif self.instance.file: dev = self.instance.file return dev class Meta: model = MSDSObject fields = ['provider', 'product', 'file']
class UserCreateForm(UserCreationForm): required_css_class = 'required' error_css_class = 'error' email = EmailField(required=True) username = CharField(label=username_label, help_text=username_help) first_name = CharField(required=True) last_name = CharField(required=True) verification = ReCaptchaField(widget=ReCaptchaWidget()) def is_valid(self): valid = super(UserCreateForm, self).is_valid() if valid: email = self.cleaned_data['email'] if User.objects.filter(email=email).count(): self._errors['email'] = 'That email address is already in use' valid = False return valid class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'password1', 'password2', ]
class UserClientForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput, label="Contraseña") password_confirm = forms.CharField(widget=forms.PasswordInput, label="Confirmación de contraseña") captcha = ReCaptchaField(widget=ReCaptchaWidget()) class Meta: parsley_extras = { 'password': { 'minlength': "5", }, 'password_confirm': { 'equalto': "password", 'error-message': "Las contraseñas ingresadas no son iguales", }, } labels = { 'first_name': 'Nombre', 'last_name': 'Apellido', 'email': 'Email', 'direction': 'Direccion', } model = UserProfile fields = ('first_name', 'last_name', 'email', 'direction')
def get_captcha_field(): engine = settings.MULTI_CAPTCHA_ADMIN['engine'] if engine == 'simple-captcha': from captcha.fields import CaptchaField return CaptchaField() elif engine == 'recaptcha': from captcha.fields import ReCaptchaField return ReCaptchaField() elif engine == 'recaptcha3': from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV3 return ReCaptchaField(widget=ReCaptchaV3) elif engine == 'recaptcha2_snow': from snowpenguin.django.recaptcha2.fields import ReCaptchaField from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget return ReCaptchaField(widget=ReCaptchaWidget()) elif engine == 'recaptcha3_snow': from snowpenguin.django.recaptcha3.fields import ReCaptchaField from snowpenguin.django.recaptcha3.widgets import ReCaptchaHiddenInput return ReCaptchaField(widget=ReCaptchaHiddenInput())
class SignUpForm(UserCreationForm): class Meta: model = User fields = ( 'username', 'first_name', 'email', 'password1', 'password2', 'recaptcha2', ) first_name = forms.CharField( max_length=30, required=False, help_text='Optional.', label="Nickname" ) email = forms.EmailField( max_length=254, required=False, help_text='Optional' ) recaptcha2 = ReCaptchaField( label='Spam check', widget=ReCaptchaWidget(), )
class UserRegistrationForm(forms.ModelForm): captcha = ReCaptchaField(widget=ReCaptchaWidget()) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') def __init__(self, *args, **kwargs): super(UserRegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].help_text = "Enter a username." self.fields['first_name'].help_text = "Enter your first name." self.fields['last_name'].help_text = "Enter your last name." self.fields['email'].help_text = "Enter your email address." self.fields['password'].help_text = "Enter a password." self.fields['password'].widget = forms.PasswordInput() def clean(self): data = super(UserRegistrationForm, self).clean() username = data.get('username') first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') password = data.get('password') if not (username and first_name and last_name and email and password): self.error_class(['Please fill out all of the fields.']) try: User.objects.get(username=username) self.error_class(['Someone already has that username.']) except User.DoesNotExist: pass return data
class ContactForm(forms.ModelForm): full_name = forms.CharField(label=_('Name and Surname'), max_length=100) email = forms.EmailField(label=_('Email Address')) message = forms.CharField(label=_('Your Message'), widget=forms.Textarea) recaptcha = ReCaptchaField(widget=ReCaptchaWidget(explicit=True)) class Meta: model = Contact fields = ('full_name', 'email', 'message', 'recaptcha') def save(self, activity=None, request=None, commit=True): contact = super(ContactForm, self).save(commit=False) if commit and activity: try: contact = Contact(full_name=self.cleaned_data.get('full_name'), email=self.cleaned_data.get('email'), message=self.cleaned_data.get('message'), activity=activity) contact.save() # Send Contact Mail domain = request.META.get('HTTP_ORIGIN', None) users = User.objects.filter(is_superuser=True) for user in users: MailModule.send_contact_mail(contact, user, domain) except: contact = None return contact
class UserForm(UserCreationForm): """ Class for the creation of the form with the data of the user and that is used for the creation of the user """ captcha = ReCaptchaField(widget=ReCaptchaWidget()) class Meta: model = get_user_model() fields = [ 'email', ] labels = { 'email': 'Correo electrónico', } widgets = { 'email': forms.EmailInput( attrs={ 'class': 'form-control', 'placeholder': 'Correo electrónico', 'pattern': '^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$', }), }
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 EmailCollectionForm(forms.Form): email = forms.EmailField(label="Enter your email", required=True) captcha = ReCaptchaField(widget=ReCaptchaWidget()) def __init__(self, *args, **kwargs): super(EmailCollectionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = "font-weight-bold" self.helper.form_error_title = "Oops" self.helper.add_input( Submit('submit', 'Submit', css_class="btn-block") ) def clean_email(self): validate_email(self.cleaned_data['email']) if not UserExistsByEmail(self.cleaned_data['email']): raise ValidationError("An account with the given email doesn't exist") return self.cleaned_data['email']
class RegistrationForm(forms.Form): captcha = ReCaptchaField( widget=ReCaptchaWidget(attrs={'class': 'validate'}), label="") name = forms.CharField(label='Họ và tên', max_length=50) username = forms.CharField(label='Tài khoản', max_length=30) email = forms.EmailField(label='email') address = forms.CharField(label='Địa chỉ', max_length=60) password = forms.CharField(label='Mật khẩu', widget=forms.PasswordInput()) password2 = forms.CharField(label='Nhập lại mật khẩu', widget=forms.PasswordInput()) def clean_password2(self): if 'password' in self.cleaned_data: password = self.cleaned_data['password'] password2 = self.cleaned_data['password2'] if password == password2 and password: return password2 raise forms.ValidationError("Mật khẩu không hợp lệ") def clean_username(self): username = self.cleaned_data['username'] if not re.search(r'^\w+$', username): raise forms.ValidationError("Tên tài khoản có ký tự đặc biệt") try: User.objects.get(username=username) except ObjectDoesNotExist: return username raise forms.ValidationError("Tài khoản đã tồn tại") def save(self): User.objects.create_user(username=self.cleaned_data['username'], email=self.cleaned_data['email'], password=self.cleaned_data['password'])
class UserRegisterForm(UserCreationForm): email = forms.EmailField() captcha = ReCaptchaField(widget=ReCaptchaWidget()) class Meta: model = User fields = ['username', 'email', 'password1', 'password2']
class ContactForm(forms.ModelForm): full_name = forms.CharField(label=_('Name and Surname'), max_length=100) email = forms.EmailField(label=_('E-Mail Address')) message = forms.CharField(label=_('Your Message'), widget=forms.Textarea) recaptcha = ReCaptchaField(widget=ReCaptchaWidget(explicit=True)) class Meta: model = Contact fields = ('full_name', 'email', 'message', 'recaptcha') def save(self, activity=None, commit=True): contact = super(ContactForm, self).save(commit=False) if commit and activity: try: contact = Contact(full_name=self.cleaned_data.get('full_name'), email=self.cleaned_data.get('email'), message=self.cleaned_data.get('message'), activity=activity) contact.save() except: contact = None return contact
def __init__(self, *args, **kwargs): bad_logins = kwargs.pop('bad_logins', None) super(LoginForm, self).__init__(*args, **kwargs) if bad_logins >= 3 and (settings.CAPTCHA_TYPE == 'simple_math' or settings.CAPTCHA_TYPE == 'recaptcha'): self.fields['captcha'] = ReCaptchaField(widget=ReCaptchaWidget()) else: self.fields['captcha'] = forms.CharField(widget=forms.HiddenInput(), required=False)
class CodeSchoolForm(forms.Form): name = CharField(label='School Name') url = CharField(label='School website url') fulltime = BooleanField(label='Fulltime available?', required=False) hardware = BooleanField(label='Hardware included?', required=False) has_online = BooleanField(label='Online Offered?', required=False) only_online = BooleanField(label='Online only?', required=False) accredited = BooleanField(label='VA Accredited?', required=False) housing = BooleanField(label='Housing Included?', required=False) mooc = BooleanField(label='MOOC Only?', required=False) rep_name = CharField(label='School Representative') rep_email = CharField(label='Representative Email') address1 = CharField(label='Address Line 1') address2 = CharField(label='Address Line 2') city = CharField(label='City') state = CharField(label='State') zipcode = CharField(label='Zipcode') country = CharField(label='Country') logo = ImageField(label='Logo', validators=[image_validator]) recaptcha = ReCaptchaField(private_key=settings.RECAPTCHA_PRIVATE_KEY, widget=ReCaptchaWidget())
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 LoginForm(forms.Form): email = forms.EmailField( required=True, widget=forms.EmailInput, label="Email" ) password = forms.CharField( required=True, widget=forms.PasswordInput, label="Password" ) captcha = ReCaptchaField(widget=ReCaptchaWidget()) def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = "font-weight-bold" self.helper.form_error_title = "Oops" self.helper.add_input( Submit('login', 'Login', css_class="btn-block") )
class RecaptchaRegistrationForm(SignupForm): tos = forms.BooleanField( widget=forms.CheckboxInput, label=_('I have read and agree to the Terms of Service'), error_messages={ 'required': _("You must agree to the terms to register") }) captcha = ReCaptchaField(widget=ReCaptchaWidget()) @staticmethod def is_email_blacklisted(email): try: sfs_url = f'http://api.stopforumspam.org/api?email={email}' contents = urllib.request.urlopen(sfs_url).read() return b'<appears>yes</appears>' in contents except Exception: return any([ email.lower().endswith('@' + d) for d in settings.BLACKLISTED_DOMAINS ]) def save(self, request): user = super().save(request) email = self.cleaned_data.get("email") if email and self.is_email_blacklisted(email): user.is_active = False user.save() return user
class AskForm(forms.Form): """ Форма для создания вопроcа :func:`home.views.ask` :param Name: поле ввода имени :param Email: поле ввода email'a :param Question: поле ввода вопроса :param recaptcha: recaptcha v3 """ Name = forms.CharField( widget=forms.TextInput(attrs={ "class": "form-control", "id": "materialContactFormName", }), required=True) Email = forms.CharField( widget=forms.TextInput(attrs={ "class": "form-control", "id": "materialContactFormEmail", }), required=True) Question = forms.CharField(widget=forms.Textarea( attrs={ "class": 'form-control md-textarea', 'id': 'materialContactFormMessage', 'rows': '3', }), required=True) recaptcha = ReCaptchaField(widget=ReCaptchaWidget(), required=True)
class AllauthSignupForm(forms.Form): captcha = ReCaptchaField(widget=ReCaptchaWidget()) def signup(self, request, user): """ Required, or else it throws deprecation warnings """ pass
class RegistrationFormWithCaptcha(RegistrationForm): class Meta(RegistrationForm.Meta): model = User fields = ('first_name', 'last_name', 'organisation', 'email', ) captcha = ReCaptchaField(widget=ReCaptchaWidget(explicit=True, container_id='recaptcha-id')) def __init__(self, *args, **kwargs): self.helper = self._crispy_helper() super().__init__(*args, **kwargs) for f in ['first_name', 'last_name']: self.fields[f].required = True def _crispy_helper(self): """ Create the crispy-forms FormHelper. The form will then be rendered using {% crispy form %} in the template. """ helper = FormHelper() helper.attrs['id'] = 'id_user_as_form' helper.layout = Layout( AppendedText('email', '<span class="fa fa-envelope"/>'), AppendedText('first_name', '<span class="fa fa-user"/>'), AppendedText('last_name', '<span class="fa fa-user"/>'), AppendedText('organisation', '<span class="fa fa-briefcase"/>'), AppendedText('password1', '<span class="fa fa-lock"/>'), AppendedText('password2', '<span class="fa fa-repeat"/>'), 'captcha', Submit('register', 'Register', css_class='btn-block'), ) return helper
class ContactUsForm(forms.ModelForm): captcha = ReCaptchaField(widget=ReCaptchaWidget()) class Meta: model = ContactUs fields = ['name', 'contact', 'email', 'subject', 'message','captcha'] name = forms.CharField( max_length=225, required=True, widget=forms.TextInput( attrs={'type': 'text', 'name': 'name', 'class': 'form-control', 'id': 'exampleInputName1', 'placeholder': 'Enter Name' } ) ) contact = forms.IntegerField( required=True, widget=forms.NumberInput( attrs={'type': 'number', 'name': 'contact', 'class': 'form-control', 'id': 'exampleInputcontact1', 'placeholder': 'Enter Contact No' } ) ) email = forms.EmailField( max_length=50, required=True, widget=forms.EmailInput( attrs={'type': 'email', 'name': 'email', 'class': 'form-control', 'id': 'exampleInputEmail1', 'placeholder': 'Enter Email'} ) ) subject = forms.CharField( max_length=225, required=True, widget=forms.TextInput( attrs={'type': 'text', 'name': 'subject', 'class': 'form-control', 'id': 'exampleInputsub1', 'placeholder': 'Enter Subject'} ) ) message = forms.CharField( required=True, widget=forms.Textarea( attrs={'class': 'form-control', 'name': 'message', 'id': 'message', 'rows': '5' } ), )
class CaptchaContactForm(ModelForm): captcha = ReCaptchaField(widget=ReCaptchaWidget()) ''' Cpatcha enabled default form model for collect contact data. ''' class Meta: model = SimpleContact fields = ('from_name', 'from_email', 'from_phone', 'message')
def __init__(self, captcha, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.to = settings.CONTACT_FORM_RECIPIENTS self.fields['name'].label = _('Name') self.fields['email'].label = _('Email') self.fields['body'].label = _('Message') if captcha: self.fields['captcha'] = ReCaptchaField(widget=ReCaptchaWidget())
def __init__(self, captcha, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.to = settings.CONTACT_FORM_RECIPIENTS self.fields["name"].label = _("Name") self.fields["email"].label = _("Email") self.fields["body"].label = _("Message") if captcha: self.fields["captcha"] = ReCaptchaField(widget=ReCaptchaWidget())
class SimpleCaptchaContactForm(ModelForm): captcha = ReCaptchaField(widget=ReCaptchaWidget(explicit=True)) ''' Cpatcha enabled simplified contact form, ignore phone input. ''' class Meta: model = SimpleContact fields = ('from_name', 'from_email', 'message')
class ContactForm(forms.ModelForm): class Meta: model = Contact fields = [ 'first_name', 'last_name', 'phone', 'email', 'comment', ] cc_myself = forms.BooleanField(required=False, initial=False) captcha = ReCaptchaField(label=" ", widget=ReCaptchaWidget()) def send_email(self, request=None): emails = [ EmailMultiAlternatives( **{ 'subject': 'Contact Form: ' + str(self.instance.name), 'to': [mkemail(*a) for a in settings.ADMINS], 'reply_to': [ mkemail(str(self.instance.name), self.cleaned_data['email']) ], 'body': str().join('{0:15s} : {1}\n'.format( self.fields[f].label, self.cleaned_data[f]) for f in self._meta.fields), }) ] emails[0].attach_alternative( render_to_string('contact/email.html', context={ 'name': str(self.instance.name), 'phone': self.cleaned_data['phone'], 'email': self.cleaned_data['email'], 'comment': self.cleaned_data['comment'], }, request=request), 'text/html') if self.cleaned_data['cc_myself']: emails.append(copy.copy(emails[0])) emails[1].to = emails[0].reply_to emails[1].reply_to = [settings.DEFAULT_REPLY_ADDR] try: with get_connection() as con: con.send_messages(emails) con.close() except BadHeaderError as e: return HttpResponse(' '.join(['BadHeaderError:'] + list(e.args))) except Exception as e: # pragma: no cover print(e) return False return True
class ReSignUpForm(forms.Form): first_name = forms.CharField(max_length=255, label='First Name') last_name = forms.CharField(max_length=255, label='Last Name') captcha = ReCaptchaField(widget=ReCaptchaWidget()) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save()
def __init__(self, user, *args, **kwargs): self.user = user super(CaptchaForm, self).__init__(*args, **kwargs) not_trusted = True #self.user.is_authenticated and (not self.user.profile.trusted) # Untrusted users get a recaptcha field if settings.RECAPTCHA_PRIVATE_KEY and not_trusted: self.fields["captcha"] = ReCaptchaField(widget=ReCaptchaWidget())