class TwitchForm(forms.Form): username = forms.CharField(label='Nazwa użytkownika na Twitch.tv') captcha = ReCaptchaField()
class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_length=30, required=True) email = forms.EmailField(max_length=254, required=True) organization = forms.CharField(max_length=255, required=True) phone_regex = RegexValidator( regex=r'^\d{8,15}$', message=_("Please enter your phone number correctly!")) phone_number = forms.CharField(validators=[phone_regex], required=False) age = forms.IntegerField(required=False) captcha = ReCaptchaField() def is_valid(self): if not super().is_valid(): return False if not settings.ENABLE_REGISTRATION: self.add_error(None, _('Registration is closed. See you next year.')) return False return True def save(self, commit=True): user = super().save(commit=False) user.is_active = False if commit: user.save() domain = get_current_site(self.request) email_text = render_to_string( 'email/acc_active.txt', { 'user': user, 'domain': domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) email_html = render_to_string( 'email/acc_active.html', { 'user': user, 'domain': domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) profile = Profile(user=user, phone_number=self.cleaned_data['phone_number'], organization=self.cleaned_data['organization'], age=self.cleaned_data['age']) profile.save() send_mail(subject='Activate Your Account', message=email_text, from_email='Sharif AI Challenge <*****@*****.**>', recipient_list=[user.email], fail_silently=False, html_message=email_html) return user class Meta: model = User fields = ('username', 'first_name', 'last_name', 'organization', 'age', 'phone_number', 'email', 'password1', 'password2')
class BusinessAddForm(forms.Form): name = forms.CharField( label=_('Company name'), max_length=255, help_text=_('The name of the company.'), widget=forms.TextInput( attrs={'class': 'form-control form-control-sm'})) description = forms.CharField( label=_('Description'), help_text=_('A short description of the services of the company.'), widget=forms.Textarea(attrs={ 'class': 'form-control form-control-sm', 'rows': 5 })) address = forms.CharField( label=_('Street and number'), max_length=255, help_text=_('The street and street number of your address'), widget=forms.TextInput( attrs={'class': 'form-control form-control-sm'})) location = forms.ModelChoiceField( label=_('City'), help_text=_('Where is the company based?'), queryset=NPA.objects.all(), widget=forms.Select(attrs={'class': 'form-control form-control-sm'})) category = forms.CharField( label=_('Categories'), max_length=255, help_text= _('List possible categories of the service that the company provides (eg. Food, Books, Drinks, Music, Games, Mobility)' ), widget=forms.TextInput( attrs={'class': 'form-control form-control-sm'})) delivery = forms.CharField( label=_('Delivery locations'), max_length=255, help_text= _('Where are you delivering ? Whole Switzerland, cantons, districts, municipalities, be as precise as possible.' ), widget=forms.TextInput( attrs={'class': 'form-control form-control-sm'})) website = forms.CharField( label=_('Website'), max_length=255, help_text=_('Company website, if any.'), required=False, widget=forms.TextInput( attrs={'class': 'form-control form-control-sm'})) phone = forms.CharField( label=_('Phone number'), max_length=100, help_text=_('Company phone number, if any.'), required=False, widget=forms.TextInput( attrs={'class': 'form-control form-control-sm'})) email = forms.CharField( label=_('Email address'), max_length=255, help_text=_('Company email address, if any.'), required=False, widget=forms.TextInput( attrs={'class': 'form-control form-control-sm'})) if os.environ.get("RUNNING_ENV", default='dev') != 'dev': captcha = ReCaptchaField(label='') def get_location_choices(self): return [(0, 'Test')] def save_request(self): location = str(self.cleaned_data['location']) + ' [PK:' + str( self.cleaned_data['location'].pk) + ']' # Create request r = Request(name=self.cleaned_data['name'], description=self.cleaned_data['description'], address=self.cleaned_data['address'], location=location, website=self.cleaned_data['website'], phone=self.cleaned_data['phone'], email=self.cleaned_data['email'], category=self.cleaned_data['category'], delivery=self.cleaned_data['delivery'], source=1, checksum='Web Form', source_uuid=str(uuid.uuid4()), lang=get_language()) r.save() # Set status r.set_status(r.events.NEW)
class AcceptInvitationForm(forms.Form): captcha = ReCaptchaField(attrs={'theme': 'clean'})
class FeedbackAnonymousForm(FeedbackRegisteredForm): """ Feedback form used for anonymous users (has additionally a reCaptcha field) """ captcha = ReCaptchaField(label=_('Confirmation text'), help_text=_('As a security measure, please enter the previous words'),)
class SignupForm(forms.ModelForm): username = forms.CharField(label='', max_length=100, widget=forms.TextInput( attrs={ 'type': 'text', 'class': 'input', 'id': 'username', 'name': 'username', 'placeholder': "Enter your username", 'maxlength': 100, 'required': True })) email = forms.EmailField(label='', widget=forms.TextInput( attrs={ 'type': 'email', 'class': 'input', 'id': 'email', 'name': 'email', 'placeholder': 'Email', 'maxlength': 100, 'required': True })) password = forms.CharField(label='', max_length=100, widget=forms.PasswordInput( attrs={ 'type': 'password', 'class': 'input', 'id': 'password', 'name': 'password', 'placeholder': 'Password', 'maxlength': 100, 'required': True })) password2 = forms.CharField(label='', max_length=100, widget=forms.PasswordInput( attrs={ 'type': 'password', 'class': 'input', 'id': 'password2', 'name': 'password', 'placeholder': 'Password', 'maxlength': 100, 'required': True })) captcha = ReCaptchaField(label='', widget=ReCaptchaV2Checkbox(attrs={})) class Meta: model = user_model fields = [ 'username', 'email', 'password', 'password2', ] def clean(self, *args, **kwargs): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') email_qs = user_model.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError('Email is already used') if password != password2: raise forms.ValidationError('Passwords must match!') return super(SignupForm, self).clean()
) target_node = forms.CharField( help_text=_("Example: Alpha in Ancient Greek"), max_length=255, label=_('Target Node'), ) type_of_edge = forms.ChoiceField( widget=forms.RadioSelect(), choices=EDGE_TYPE_CHOICES, label=_('Type of Edge'), ) resource = forms.CharField( help_text=_("Example: Sevan Nişanyan's Elifin Öküzü"), max_length=255, label=_('Resource'), ) <<<<<<< HEAD captcha = ReCaptchaField() ======= >>>>>>> 1115d5ca7b1d2089557455b4835ca013d9ed1152 class Search(forms.Form): search=forms.CharField( max_length=255, ) <<<<<<< HEAD ======= >>>>>>> 1115d5ca7b1d2089557455b4835ca013d9ed1152
class CaptchaUserCreationForm(UserCreationForm): """ a user creation form with a captcha """ captcha = ReCaptchaField(label="¿Eres humano?", )
class WorkshopInquiryRequestExternalForm(WorkshopInquiryRequestBaseForm): captcha = ReCaptchaField() class Meta(WorkshopInquiryRequestBaseForm.Meta): fields = WorkshopInquiryRequestBaseForm.Meta.fields + ("captcha", )
class SelfOrganisedSubmissionExternalForm(SelfOrganisedSubmissionBaseForm): captcha = ReCaptchaField() class Meta(SelfOrganisedSubmissionBaseForm.Meta): fields = SelfOrganisedSubmissionBaseForm.Meta.fields + ("captcha", )
class TrainingRequestForm(forms.ModelForm): # agreement fields are moved to the model captcha = ReCaptchaField() helper = BootstrapHelper(wider_labels=True, add_cancel_button=False) class Meta: model = TrainingRequest fields = ( 'review_process', 'group_name', 'personal', 'family', 'email', 'secondary_email', 'github', 'occupation', 'occupation_other', 'affiliation', 'location', 'country', 'underresourced', 'domains', 'domains_other', 'underrepresented', 'underrepresented_details', 'nonprofit_teaching_experience', 'previous_involvement', 'previous_training', 'previous_training_other', 'previous_training_explanation', 'previous_experience', 'previous_experience_other', 'previous_experience_explanation', 'programming_language_usage_frequency', 'teaching_frequency_expectation', 'teaching_frequency_expectation_other', 'max_travelling_frequency', 'max_travelling_frequency_other', 'reason', 'user_notes', 'data_privacy_agreement', 'code_of_conduct_agreement', 'training_completion_agreement', 'workshop_teaching_agreement', ) widgets = { 'review_process': forms.RadioSelect(), 'occupation': RadioSelectWithOther('occupation_other'), 'domains': CheckboxSelectMultipleWithOthers('domains_other'), 'underrepresented': forms.RadioSelect(), 'previous_involvement': forms.CheckboxSelectMultiple(), 'previous_training': RadioSelectWithOther('previous_training_other'), 'previous_experience': RadioSelectWithOther('previous_experience_other'), 'programming_language_usage_frequency': forms.RadioSelect(), 'teaching_frequency_expectation': RadioSelectWithOther('teaching_frequency_expectation_other'), 'max_travelling_frequency': RadioSelectWithOther('max_travelling_frequency_other'), 'country': Select2Widget, } def __init__(self, *args, initial_group_name=None, **kwargs): initial = kwargs.pop('initial', {}) if initial_group_name is not None: initial['group_name'] = initial_group_name initial['review_process'] = 'preapproved' super().__init__(*args, initial=initial, **kwargs) if initial_group_name is not None: field = self.fields['group_name'] field.widget = field.hidden_widget() # set up a layout object for the helper self.helper.layout = self.helper.build_default_layout(self) # set up RadioSelectWithOther widget so that it can display additional # field inline self['occupation'].field.widget.other_field = self['occupation_other'] self['domains'].field.widget.other_field = self['domains_other'] self['previous_training'].field.widget.other_field = ( self['previous_training_other']) self['previous_experience'].field.widget.other_field = ( self['previous_experience_other']) self['teaching_frequency_expectation'].field.widget.other_field = ( self['teaching_frequency_expectation_other']) self['max_travelling_frequency'].field.widget.other_field = ( self['max_travelling_frequency_other']) # remove that additional field self.helper.layout.fields.remove('occupation_other') self.helper.layout.fields.remove('domains_other') self.helper.layout.fields.remove('previous_training_other') self.helper.layout.fields.remove('previous_experience_other') self.helper.layout.fields.remove( 'teaching_frequency_expectation_other') self.helper.layout.fields.remove('max_travelling_frequency_other') # fake requiredness of the registration code / group name self['group_name'].field.widget.fake_required = True # special accordion display for the review process self['review_process'].field.widget.subfields = { 'preapproved': [ self['group_name'], ], 'open': [], # this option doesn't require any additional fields } self['review_process'].field.widget.notes = \ TrainingRequest.REVIEW_CHOICES_NOTES # get current position of `review_process` field pos_index = self.helper.layout.fields.index('review_process') self.helper.layout.fields.remove('review_process') self.helper.layout.fields.remove('group_name') # insert div+field at previously saved position self.helper.layout.insert( pos_index, Div( Field('review_process', template="bootstrap4/layout/radio-accordion.html"), css_class='form-group row', ), ) # add <HR> around "underrepresented*" fields index = self.helper.layout.fields.index('underrepresented') self.helper.layout.insert(index, HTML(self.helper.hr())) index = self.helper.layout.fields.index('underrepresented_details') self.helper.layout.insert(index + 1, HTML(self.helper.hr())) def clean(self): super().clean() errors = dict() # 1: validate registration code / group name review_process = self.cleaned_data.get('review_process', '') group_name = self.cleaned_data.get('group_name', '').split() # it's required when review_process is 'preapproved', but not when # 'open' if review_process == 'preapproved' and not group_name: errors['review_process'] = ValidationError( "Registration code is required for pre-approved training " "review process.") # it's required to be empty when review_process is 'open' if review_process == 'open' and group_name: errors['review_process'] = ValidationError( "Registration code must be empty for open training review " "process.") if errors: raise ValidationError(errors)
class RegistrationFormCaptcha(RegistrationForm): captcha = ReCaptchaField()
class RegistrationForm(forms.ModelForm): captcha = ReCaptchaField() class Meta: model = Registration fields = ( 'lichess_username', 'email', 'classical_rating', 'has_played_20_games', 'already_in_slack_group', 'previous_season_alternate', 'can_commit', 'friends', 'avoid', 'agreed_to_rules', 'alternate_preference', 'section_preference', 'weeks_unavailable', ) labels = { 'lichess_username': _(u'Your Lichess Username'), 'email': _(u'Your Email'), } def __init__(self, *args, **kwargs): self.season = kwargs.pop('season') league = self.season.league super(RegistrationForm, self).__init__(*args, **kwargs) # Rating fields rating_type = league.get_rating_type_display() self.fields['classical_rating'] = forms.IntegerField(required=True, label=_(u'Your Lichess %s Rating' % rating_type)) # 20 games self.fields['has_played_20_games'] = forms.TypedChoiceField(required=True, choices=YES_NO_OPTIONS, widget=forms.RadioSelect, coerce=lambda x: x == 'True', label=_(u'Is your %s rating established (not provisional)?' % rating_type.lower()), help_text=_(u'If it is provisional, it must be established ASAP by playing more games.'),) # In slack self.fields['already_in_slack_group'] = forms.TypedChoiceField(required=True, label=_(u'Are you on our Slack group?'), choices=YES_NO_OPTIONS, widget=forms.RadioSelect, coerce=lambda x: x == 'True') # Previous season status if league.competitor_type == 'team': self.fields['previous_season_alternate'] = forms.ChoiceField(required=True, choices=PREVIOUS_SEASON_ALTERNATE_OPTIONS, widget=forms.RadioSelect, label=_(u'Were you an alternate for the previous season?')) else: del self.fields['previous_season_alternate'] # Can commit time_control = league.time_control if league.rating_type != 'blitz': self.fields['can_commit'] = forms.TypedChoiceField(required=True, choices=YES_NO_OPTIONS, widget=forms.RadioSelect, coerce=lambda x: x == 'True', label=_(u'Are you able to commit to 1 long time control game (%s currently) of %s chess on Lichess.org per week?' % (time_control, league.rating_type))) else: start_time = '' if self.season.start_date is None else \ ' on %s at %s UTC' % (self.season.start_date.strftime('%b %-d'), self.season.start_date.strftime('%H:%M')) self.fields['can_commit'] = forms.TypedChoiceField(required=True, choices=YES_NO_OPTIONS, widget=forms.RadioSelect, coerce=lambda x: x == 'True', label=_(u'Are you able to commit to playing %d rounds of %s blitz games back to back%s?' % (self.season.rounds, time_control, start_time))) # Friends and avoid if league.competitor_type == 'team': self.fields['friends'] = forms.CharField(required=False, label=_(u'Are there any friends you would like to be paired with?'), help_text=_(u'Note: Please enter their exact lichess usernames. All players must register. All players must join Slack. All players should also request each other.')) self.fields['avoid'] = forms.CharField(required=False, label=_(u'Are there any players you would like NOT to be paired with?'), help_text=_(u'Note: Please enter their exact lichess usernames.')) else: del self.fields['friends'] del self.fields['avoid'] # Agree to rules rules_doc = LeagueDocument.objects.filter(league=league, type='rules').first() if rules_doc is not None: doc_url = reverse('by_league:document', args=[league.tag, rules_doc.tag]) rules_help_text = _(u'<a target="_blank" href="%s">Rules Document</a>' % doc_url) else: rules_help_text = '' league_name = league.name if not league_name.endswith('League'): league_name += ' League' self.fields['agreed_to_rules'] = forms.TypedChoiceField(required=True, label=_(u'Do you agree to the rules of the %s?' % league_name), help_text=rules_help_text, choices=YES_NO_OPTIONS, widget=forms.RadioSelect, coerce=lambda x: x == 'True') # Alternate preference if league.competitor_type == 'team': self.fields['alternate_preference'] = forms.ChoiceField(required=True, choices=ALTERNATE_PREFERENCE_OPTIONS, widget=forms.RadioSelect, label=_(u'Are you interested in being an alternate or a full time player?'), help_text=_(u'If you register late, you may start as an alternate anyway.')) else: del self.fields['alternate_preference'] section_list = self.season.section_list() if len(section_list) > 1: section_options = [('', 'No preference (use my rating)')] section_options += [(s.section.id, s.section.name) for s in section_list] self.fields['section_preference'] = forms.ChoiceField(required=False, choices=section_options, widget=forms.RadioSelect, label=_(u'Which section would you prefer to play in?'), help_text=_(u'You may be placed in a different section depending on eligibility.')) else: del self.fields['section_preference'] # Weeks unavailable if self.season.round_duration == timedelta(days=7): weeks = [(r.number, 'Round %s (%s - %s)' % (r.number, r.start_date.strftime('%b %-d') if r.start_date is not None else '?', r.end_date.strftime('%b %-d') if r.end_date is not None else '?')) for r in self.season.round_set.order_by('number')] toggle_attrs = { 'data-toggle': 'toggle', 'data-on': 'Unavailable', 'data-off': 'Available', 'data-onstyle': 'default', 'data-offstyle': 'success', 'data-size': 'small', } self.fields['weeks_unavailable'] = forms.MultipleChoiceField(required=False, label=_(u'Indicate any rounds you would not be able to play.'), choices=weeks, widget=forms.CheckboxSelectMultiple(attrs=toggle_attrs)) else: del self.fields['weeks_unavailable'] # Captcha if settings.DEBUG: del self.fields['captcha'] def save(self, commit=True, *args, **kwargs): registration = super(RegistrationForm, self).save(commit=False, *args, **kwargs) registration.season = self.season registration.status = 'pending' if commit: registration.save() return registration def clean_weeks_unavailable(self): upcoming_rounds = [r for r in self.season.round_set.order_by('number') if r.start_date > timezone.now()] upcoming_rounds_available = [r for r in upcoming_rounds if str(r.number) not in self.cleaned_data['weeks_unavailable']] upcoming_rounds_unavailable = [r for r in upcoming_rounds if str(r.number) in self.cleaned_data['weeks_unavailable']] if len(upcoming_rounds_available) == 0 and len(upcoming_rounds_unavailable) > 0: raise ValidationError('You can\'t mark yourself as unavailable for all upcoming rounds.') return ','.join(self.cleaned_data['weeks_unavailable']) def clean_section_preference(self): if self.cleaned_data['section_preference'] == '': return None return Section.objects.get(pk=int(self.cleaned_data['section_preference']))
def get_form(self, data=None, files=None, **kwargs): frm = super().get_form(data, files, **kwargs) frm.fields['captcha'] = ReCaptchaField(label='') return frm
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
class RegistrationForm(UserCreationForm): """ Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should take care when overriding ``save()`` to respect the ``commit=False`` argument, as several registration workflows will make use of it to create inactive user accounts. """ # Explicitly declared here because Django's default # UserCreationForm, which we subclass, does not require this field # but workflows in django-registration which involve explicit # activation step do require it. If you need an optional email # field, subclass and declare the field not required. captcha = ReCaptchaField() email = forms.EmailField(help_text=_(u'email address'), required=True, validators=[ validators.validate_confusables_email, ]) class Meta(UserCreationForm.Meta): fields = [User.USERNAME_FIELD, 'email', 'password1', 'password2'] required_css_class = 'required' def clean(self): """ Apply the reserved-name validator to the username. """ # This is done in clean() because Django does not currently # have a non-ugly way to just add a validator to an existing # field on a form when subclassing; the standard approach is # to re-declare the entire field in order to specify the # validator. That's not an option here because we're dealing # with the user model and we don't know -- given custom users # -- how to declare the username field. # # So defining clean() and attaching the error message (if # there is one) to the username field is the least-ugly # solution. username_value = self.cleaned_data.get(User.USERNAME_FIELD) if username_value is not None: try: if hasattr(self, 'reserved_names'): reserved_names = self.reserved_names else: reserved_names = validators.DEFAULT_RESERVED_NAMES reserved_validator = validators.ReservedNameValidator( reserved_names=reserved_names) reserved_validator(username_value) validators.validate_confusables(username_value) except ValidationError as v: self.add_error(User.USERNAME_FIELD, v) super(RegistrationForm, self).clean()
class FormWithCaptcha(forms.Form): captcha = ReCaptchaField( label='تصویر امنیتی', widget=ReCaptchaV2Checkbox(api_params={'hl': 'fa'}), error_messages={"required": "لطفا بر روی من ربات نیستم کلیک کنید"})
class CaptchaAuthenticationForm(AuthenticationForm): """ a user authentication form with a captcha """ captcha = ReCaptchaField(label="¿Eres humano?", )
class CaptchaForm(SignupForm): captcha = ReCaptchaField()
class DemoUserForm(Form): captcha = ReCaptchaField( attrs={'theme': 'clean'}, label=_('Confirmation text'), help_text=_('As a security measure, please enter the previous words'), )
class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField(max_length=30) subject = forms.CharField(max_length=50) message = forms.CharField(widget=forms.Textarea, max_length=1000) captcha = ReCaptchaField()
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 CaptchaForm(forms.Form): captcha = ReCaptchaField()
class CustomAllauthResetPasswordForm(ac_forms.ResetPasswordForm): captcha = ReCaptchaField(attrs={ 'callback': 'captcha_valid', 'expired-callback': 'captcha_expired', })
class ProfileRequestForm(forms.ModelForm): ORG_TYPE_CHOICES = LipadOrgType.objects.all().values_list( 'val', 'display_val') print('org types') #print(ORG_TYPE_CHOICES) ORDERED_FIELDS = [ 'org_type', 'organization_other', 'request_level', 'funding_source' ] captcha = ReCaptchaField(attrs={'theme': 'clean'}) #org_type = forms.ModelChoiceField( # label = _('really Type'), # queryset=LipadOrgType.objects.all(), # required=True, # to_field_name='val', #) # Instantiate choices and redefine org_type to include choices class Meta: # creates a model based on ProfileRequest from datarequests/models/profile_request.py model = ProfileRequest fields = [ 'first_name', 'middle_name', 'last_name', 'organization', # Non-commercial requester field 'org_type', 'organization_other', # Academe requester fields 'request_level', 'funding_source', 'is_consultant', 'location', 'email', 'contact_number', 'captcha' ] #ORG_TYPE_CHOICES = LipadOrgType.objects.values_list('val', 'val') # Choices that will be used for fields LOCATION_CHOICES = Choices( ('local', _('Local')), ('foreign', _('Foreign')), ) # ORGANIZATION_TYPE_CHOICES = Choices( # (0, _('Phil-LiDAR 1 SUC')), # (1, _('Phil-LiDAR 2 SUC' )), # (2, _( 'Government Agency')), # (3, _('Academe')), # (4, _( 'International NGO')), # (5, _('Local NGO')), # (6, _('Private Insitution' )), # (7, _('Other' )), # ) REQUEST_LEVEL_CHOICES = Choices( ('institution', _('Academic/ Research Institution')), ('faculty', _('Faculty')), ('student', _('Student')), ) # request_level = forms.CharField( # label=_('Level of the Request'), # required = False # ) # funding_source = forms.CharField( # label = _('Source of Funding'), # max_length=255, # required=False # ) # # is_consultant = forms.BooleanField( # required=False # ) def __init__(self, *args, **kwargs): super(ProfileRequestForm, self).__init__(*args, **kwargs) self.fields['captcha'].error_messages = { 'required': 'Please answer the Captcha to continue.' } self.fields.keyOrder = self.ORDERED_FIELDS + [ k for k in self.fields.keys() if k not in self.ORDERED_FIELDS ] print('printing fields forms.py') print(self.fields) self.helper = FormHelper() # self.helper.form_class = 'form-horizontal' self.helper.form_tag = False # self.helper.form_show_labels = False self.helper.layout = Layout( Fieldset( 'User Information', Div(Field('first_name', css_class='form-control'), css_class='form-group'), Div(Field('middle_name', css_class='form-control'), css_class='form-group'), Div(Field('last_name', css_class='form-control'), css_class='form-group'), Div(Field('organization', css_class='form-control'), css_class='form-group'), Div(Field('org_type', css_class='form-control'), css_class='form-group'), Fieldset( 'Academe', Div(Field('request_level', css_class='form-control'), css_class='form-group'), Div(Field('funding_source', css_class='form-control'), css_class='form-group'), Field('is_consultant'), css_class='academe-fieldset', ), Div(Field('organization_other', css_class='form-control'), css_class='form-group'), Div(Field('location', css_class='form-control'), css_class='form-group'), Div(Field('email', css_class='form-control'), css_class='form-group'), Div(Field('contact_number', css_class='form-control'), css_class='form-group'), ), Div(HTML("<br/><section class=widget>"), Field('captcha'), HTML("</section>")), ) def clean_first_name(self): fname = self.cleaned_data.get('first_name').strip() if len(fname) < 1: raise forms.ValidationError("You have entered an empty first name") return fname def clean_middle_name(self): mname = self.cleaned_data.get('middle_name').strip() if len(mname) < 1 or not mname: mname = '_' return mname def clean_last_name(self): lname = self.cleaned_data.get('last_name').strip() if len(lname) < 1: raise forms.ValidationError("You have entered an empty last name") return lname def clean_request_level(self): org_type = self.cleaned_data.get('org_type') print(org_type) request_level = self.cleaned_data.get('request_level') if org_type: if "Academe" in org_type and not request_level: raise forms.ValidationError("Please select the proper choice") else: return request_level else: return request_level def clean_email(self): email = self.cleaned_data.get('email') user_emails = Profile.objects.all().values_list('email', flat=True) if email in user_emails: raise forms.ValidationError( 'That email is already being used by a registered user. Please login with your account instead.' ) return email def clean_organization(self): organization = self.cleaned_data.get('organization') if len(organization) > 64: raise forms.ValidationError( 'Organization name can only be 64 characters') return organization def clean_org_type(self): org_type = self.cleaned_data.get('org_type', None) #try: # LipadOrgType.objects.get(val=org_type.val) #except Exception as e: # raise forms.ValidationError('Invalid organization type value') if not org_type: raise forms.ValidationError('Invalid organization type value') return org_type def clean_organization_other(self): organization_other = self.cleaned_data.get('organization_other') org_type = self.cleaned_data.get('org_type') print(org_type) if org_type: if (org_type == "Other" and not organization_other): raise forms.ValidationError('This field is required.') return organization_other def clean_funding_source(self): funding_source = self.cleaned_data.get('funding_source') org_type = self.cleaned_data.get('org_type') print(org_type) #intended_use_of_dataset = self.cleaned_data.get('intended_use_of_dataset') if org_type: #intended_use_of_dataset == 'noncommercial' and if "Academe" in org_type and not funding_source: raise forms.ValidationError('This field is required.') return funding_source def save(self, commit=True, *args, **kwargs): profile_request = super(ProfileRequestForm, self).save(commit=False, *args, **kwargs) profile_request.org_type = self.cleaned_data.get('org_type') if commit: profile_request.save() pprint(profile_request.org_type) return profile_request
class ReCAPTCHAForm(forms.Form): """for google reCAPTCHA API """ logger.info("ReCAPTCHA form hit") captcha = ReCaptchaField()
class DataRequestProfileForm(forms.ModelForm): captcha = ReCaptchaField(attrs={'theme': 'clean'}) class Meta: model = DataRequestProfile fields = ( 'first_name', 'middle_name', 'last_name', 'organization', # Non-commercial requester field 'organization_type', # Academe requester fields 'request_level', 'funding_source', 'is_consultant', 'location', 'email', 'contact_number', 'captcha') ORGANIZATION_TYPE_CHOICES = Choices( (0, _('Phil-LiDAR 1 SUC')), (1, _('Phil-LiDAR 2 SUC')), (2, _('Government Agency')), (3, _('Academe')), (4, _('International NGO')), (5, _('Local NGO')), (6, _('Private Insitution')), (7, _('Other')), ) REQUEST_LEVEL_CHOICES = Choices( ('institution', _('Academic/ Research Institution')), ('faculty', _('Faculty')), ('student', _('Student')), ) def __init__(self, *args, **kwargs): super(DataRequestProfileForm, self).__init__(*args, **kwargs) self.fields['captcha'].error_messages = { 'required': 'Please answer the Captcha to continue.' } self.helper = FormHelper() # self.helper.form_class = 'form-horizontal' self.helper.form_tag = False # self.helper.form_show_labels = False self.helper.layout = Layout( Fieldset( 'User Information', Div(Field('first_name', css_class='form-control'), css_class='form-group'), Div(Field('middle_name', css_class='form-control'), css_class='form-group'), Div(Field('last_name', css_class='form-control'), css_class='form-group'), Div(Field('organization', css_class='form-control'), css_class='form-group'), Div(Field('organization_type', css_class='form-control'), css_class='form-group'), Fieldset( 'Academe', Div(Field('request_level', css_class='form-control'), css_class='form-group'), Div(Field('funding_source', css_class='form-control'), css_class='form-group'), Field('is_consultant'), css_class='academe-fieldset', ), Div(Field('location', css_class='form-control'), css_class='form-group'), Div(Field('email', css_class='form-control'), css_class='form-group'), Div(Field('contact_number', css_class='form-control'), css_class='form-group'), ), Div(HTML("<br/><section class=widget>"), Field('captcha'), HTML("</section>")), ) def clean_first_name(self): fname = self.cleaned_data.get('first_name').strip() if len(fname) < 1: raise forms.ValidationError("You have entered an empty first name") return fname def clean_middle_name(self): mname = self.cleaned_data.get('middle_name').strip() if len(mname) < 1: raise forms.ValidationError( "You have entered an empty middle name") return mname def clean_last_name(self): lname = self.cleaned_data.get('last_name').strip() if len(lname) < 1: raise forms.ValidationError("You have entered an empty last name") return lname def clean_email(self): email = self.cleaned_data.get('email') user_emails = Profile.objects.all().values_list('email', flat=True) if email in user_emails: raise forms.ValidationError( 'That email is already being used by a registered user. lease login with your account instead.' ) return email def clean_organization(self): organization = self.cleaned_data.get('organization') if len(organization) > 64: raise forms.ValidationError( 'Organization name can only be 64 characters') return organization def clean_funding_source(self): funding_source = self.cleaned_data.get('funding_source') organization_type = self.cleaned_data.get('organization_type') if (organization_type == OrganizationType.ACADEME and not funding_source): raise forms.ValidationError('This field is required.') return funding_source def save(self, commit=True, *args, **kwargs): data_request = super(DataRequestProfileForm, self).save(commit=False, *args, **kwargs) if commit: data_request.save() return data_request
class YouTubeForm(forms.Form): name = forms.CharField(label='Tytuł filmu', max_length=50) video_id = forms.CharField(label='ID filmu', max_length=23) captcha = ReCaptchaField()
class CommentForm(forms.ModelForm): captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox()) class Meta: model = PostPageComments fields = ['new_comment']
class RegisterForm(forms.Form): state = forms.ChoiceField( choices=[ ('', '-- None --'), ], widget=forms.Select(attrs={}), required=True, error_messages={'required': 'State field is required.'}) #district = forms.ChoiceField(choices = [('', '-- None --'),], widget=forms.Select(attrs = {}), required = True, error_messages = {'required':'district field is required.'}) college = forms.ChoiceField( choices=[ ('', '-- None --'), ], widget=forms.Select(attrs={}), required=True, error_messages={'required': 'College Name field is required.'}) firstname = forms.CharField() lastname = forms.CharField() email = forms.EmailField() gender = forms.ChoiceField(widget=forms.RadioSelect, choices=[('Male', 'Male'), ('Female', 'Female')], required=True) password = forms.CharField(widget=forms.PasswordInput()) password_confirm = forms.CharField(widget=forms.PasswordInput()) choices = list(Course.objects.order_by('name').values_list('id', 'name')) choices.insert( 0, ('', '-- None --'), ) course = forms.ChoiceField(choices=choices) year = forms.ChoiceField(choices=( ('', '-- None --'), (1, '1st Year'), (2, '2nd year'), (3, '3rd year'), (4, '4th year'), (5, '5th year'), (6, '6th year'), (7, 'Others'), )) captcha = ReCaptchaField() def clean_username(self): username = self.cleaned_data['username'] error = 0 try: user = MdlUser.objects.filter(username=username).first().id error = 1 except: return username if error: raise forms.ValidationError(u'Username: %s already exists' % username) def clean_email(self): email = self.cleaned_data['email'].lower() error = 0 try: user = MdlUser.objects.filter(email=email).first() user.id error = 1 # check if user exists mdluser, flag, authuser = get_or_create_user(user) if flag: mdluser.password = encript_password(mdluser.firstname) mdluser.save() # send email along with password except Exception, e: return email if error: raise forms.ValidationError(u'Email: %s already exists' % email)
def recaptcha_html(): captcha = ReCaptchaField() return captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY)