class UserRegisterForm(happyforms.ModelForm, UsernameMixin, PasswordMixin): """ For registering users. We're not building off d.contrib.auth.forms.UserCreationForm because it doesn't do a lot of the details here, so we'd have to rewrite most of it anyway. """ username = forms.CharField(max_length=50) display_name = forms.CharField(label=_lazy(u'Display Name'), max_length=50, required=False) location = forms.CharField(label=_lazy(u'Location'), max_length=100, required=False) occupation = forms.CharField(label=_lazy(u'Occupation'), max_length=100, required=False) password = forms.CharField(max_length=255, min_length=PasswordMixin.min_length, error_messages=PasswordMixin.error_msg, widget=PasswordMixin.widget(render_value=False)) password2 = forms.CharField(max_length=255, widget=forms.PasswordInput(render_value=False)) recaptcha = captcha.fields.ReCaptchaField() homepage = forms.URLField(label=_lazy(u'Homepage'), required=False) class Meta: model = UserProfile fields = ('username', 'display_name', 'location', 'occupation', 'password', 'password2', 'recaptcha', 'homepage', 'email', 'emailhidden') def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) if not settings.RECAPTCHA_PRIVATE_KEY: del self.fields['recaptcha'] errors = { 'invalid': _('This URL has an invalid format. ' 'Valid URLs look like ' 'http://example.com/my_page.') } self.fields['homepage'].error_messages = errors def clean_email(self): d = self.cleaned_data['email'].split('@')[-1] if BlacklistedEmailDomain.blocked(d): raise forms.ValidationError( _('Please use an email address from a ' 'different provider to complete ' 'your registration.')) return self.cleaned_data['email'] def clean(self): super(UserRegisterForm, self).clean() data = self.cleaned_data # Passwords p1 = data.get('password') p2 = data.get('password2') # If p1 is invalid because its blocked, this message is non sensical. if p1 and p1 != p2: msg = _('The passwords did not match.') self._errors['password2'] = ErrorList([msg]) if p2: del data['password2'] return data
class InstituteForm(forms.Form): name = forms.CharField(max_length=200) logo = forms.URLField(required=False)
class FacebookPictureForm(forms.Form): facebook_photo = forms.URLField(widget=forms.HiddenInput)
class ImageUploadForm(forms.Form): url_image = forms.URLField(label='Ссылка', required=False) image = forms.ImageField(label='Файл', required=False)
class SocialProfileForm(forms.Form): github = forms.URLField(required=False) facebook = forms.URLField(required=False) linkedin = forms.URLField(required=False) codechef = forms.URLField(required=False) codeforces = forms.URLField(required=False)
class AdminForm(EntryType.AdminForm): image_url = forms.URLField() description = forms.CharField(widget=forms.Textarea, required=False)
class SearchForm(forms.Form): url = forms.URLField(widget=forms.URLInput( attrs={'placeholder': "Enter URL"}))
class RegulatorySensitiveAreaForm(CommonForm): geomfields = ['geom'] name = forms.CharField(max_length=250, label=_(u"Name")) elevation = forms.IntegerField(label=_(u"Elevation"), required=False, validators=[MinValueValidator(0)]) pictogram = forms.FileField(label=_(u"Pictogram"), required=False) period01 = forms.BooleanField(label=_(u"January"), required=False) period02 = forms.BooleanField(label=_(u"February"), required=False) period03 = forms.BooleanField(label=_(u"March"), required=False) period04 = forms.BooleanField(label=_(u"April"), required=False) period05 = forms.BooleanField(label=_(u"May"), required=False) period06 = forms.BooleanField(label=_(u"June"), required=False) period07 = forms.BooleanField(label=_(u"July"), required=False) period08 = forms.BooleanField(label=_(u"August"), required=False) period09 = forms.BooleanField(label=_(u"September"), required=False) period10 = forms.BooleanField(label=_(u"October"), required=False) period11 = forms.BooleanField(label=_(u"November"), required=False) period12 = forms.BooleanField(label=_(u"Decembre"), required=False) practices = forms.ModelMultipleChoiceField(label=_(u"Sport practices"), queryset=SportPractice.objects) url = forms.URLField(label=_(u"URL"), required=False) class Meta: fields = ['structure', 'name', 'elevation', 'published', 'description', 'contact', 'pictogram', 'practices'] + \ ['period{:02}'.format(p) for p in range(1, 13)] + ['url', 'geom'] model = SensitiveArea widgets = {'geom': PolygonMapWidget()} def __init__(self, *args, **kwargs): if kwargs['instance']: species = kwargs['instance'].species kwargs['initial'] = { 'name': species.name, 'elevation': species.radius, 'pictogram': species.pictogram, 'practices': species.practices.all(), 'url': species.url, } for p in range(1, 13): name = 'period{:02}'.format(p) kwargs['initial'][name] = getattr(species, name) super(RegulatorySensitiveAreaForm, self).__init__(*args, **kwargs) self.helper.form_action += '?category=2' def save(self): if not self.instance.pk: species = Species() else: species = self.instance.species species.category = Species.REGULATORY species.name = self.cleaned_data['name'] species.radius = self.cleaned_data['elevation'] species.pictogram = self.cleaned_data['pictogram'] species.url = self.cleaned_data['url'] for p in range(1, 13): fieldname = 'period{:02}'.format(p) setattr(species, fieldname, self.cleaned_data[fieldname]) species.save() species.practices = self.cleaned_data['practices'] area = super(RegulatorySensitiveAreaForm, self).save(commit=False) area.species = species area.save() return area
class CommonForm(NoForm): src = forms.CharField(label='Source', required=False) wiki = forms.URLField(label='URL', widget=forms.URLInput(attrs=dict(size=96)), required=False) class Meta: model = Common fields = ('name', 'src', 'wiki', 'area') # + user
class SponsorSignupForm(forms.Form): name = forms.CharField( label="Company name *", min_length=3, max_length=100, help_text="This name is used on invoices and in internal communication" ) displayname = forms.CharField( label="Display name *", min_length=3, max_length=100, help_text= "This name is displayed on websites and in public communication") address = forms.CharField( label="Company invoice address *", min_length=10, max_length=500, widget=forms.Textarea, help_text= "The sponsor name is automatically included at beginning of address. The VAT number is automatically included at end of address." ) vatstatus = forms.ChoiceField(label="Company VAT status", choices=vat_status_choices) vatnumber = forms.CharField( label="EU VAT Number", min_length=5, max_length=50, help_text= "Enter EU VAT Number to be included on invoices if assigned one. Leave empty if outside the EU or without assigned VAT number.", required=False) url = forms.URLField(label="Company URL *", validators=[ Http200Validator, ]) twittername = forms.CharField(label="Company twitter", min_length=0, max_length=100, required=False, validators=[ TwitterValidator, ]) def __init__(self, conference, *args, **kwargs): self.conference = conference super(SponsorSignupForm, self).__init__(*args, **kwargs) if not settings.EU_VAT: del self.fields['vatstatus'] del self.fields['vatnumber'] def clean_name(self): if Sponsor.objects.filter( conference=self.conference, name__iexact=self.cleaned_data['name']).exists(): raise ValidationError( "A sponsor with this name is already signed up for this conference!" ) return self.cleaned_data['name'] def clean_displayname(self): if Sponsor.objects.filter( conference=self.conference, displayname__iexact=self.cleaned_data['displayname']).exists(): raise ValidationError( "A sponsor with this display name is already signed up for this conference!" ) return self.cleaned_data['displayname'] def clean_vatnumber(self): # EU VAT numbers begin with a two letter country-code, so let's # validate that first v = self.cleaned_data['vatnumber'].upper().replace(' ', '') if v == "": # We allow empty VAT numbers, for sponsors from outside of # europe. return v if not EuropeCountry.objects.filter(iso=v[:2]).exists(): raise ValidationError( "VAT numbers must begin with the two letter country code") if settings.EU_VAT_VALIDATE: from . import vatutil r = vatutil.validate_eu_vat_number(v) if r: raise ValidationError("Invalid VAT number: %s" % r) return v def clean(self): cleaned_data = super(SponsorSignupForm, self).clean() if settings.EU_VAT: if int(cleaned_data['vatstatus']) == 0: # Company inside EU and has VAT number if not cleaned_data.get('vatnumber', None): self.add_error( 'vatnumber', 'VAT number must be specified for companies inside EU with VAT number' ) elif int(cleaned_data['vatstatus']) == 1: # Company inside EU but without VAT number if cleaned_data.get('vatnumber', None): self.add_error( 'vatnumber', 'VAT number should not be specified for companies without one!' ) else: # Company outside EU if cleaned_data.get('vatnumber', None): self.add_error( 'vatnumber', 'VAT number should not be specified for companies outside EU' ) return cleaned_data
class OPMLEntry(forms.Form): enabled = forms.BooleanField() title = forms.CharField() feedurl = forms.URLField() wwwurl = forms.URLField()
class PostProjectForm(PostForm): title = forms.CharField( label="Название проекта", required=True, max_length=128, widget=forms.TextInput(attrs={"placeholder": "Название проекта 🏗"}), ) url = forms.URLField( label="Ссылка на страницу проекта 👇", required=True, widget=forms.TextInput(attrs={"placeholder": "https://"}), ) image = ImageUploadField( label="Скриншот или иконка", required=True, resize=(1024, 1024), ) text = forms.CharField( label="Описание", required=True, min_length=1500, initial="🤗 Расскажите нам все инсайды о вашем проекте.\n\n " "Ниже мы накидали список популярных вопросов, на которые обычно всем интересно услышать ответы. " "Он здесь для того, чтобы помочь вам с проблемой чистого листа и задать базовую структуру. " "Не нужно понимать его буквально. Главное — чтобы другим было полезно читать ваш опыт.\n\n" "⚠️ И еще раз: короткие односложные ответы на вопросы не считаются хорошим рассказом о проекте " "и будут расценены модераторами как спам. Нам интересен именно ваш опыт и истории, " "а не технические ответы на вопросы!\n\n" "### Расскажите о себе и сути проекта?\n\n\n\n" "### Как появилась идея? Что вдохновило?\n\n\n\n" "### Что вошло в прототип и сколько времени на него было потрачено?\n\n\n\n" "### Какой технологический стек вы использовали? Почему?\n\n\n\n" "### Как вы запускались и искали первых пользователей?\n\n\n\n" "### С какими самыми неожиданными трудностями пришлось столкнуться?\n\n\n\n" "### Сколько потратили и заработали? Есть идеи как это можно монетизировать?\n\n\n\n" "### Какие планы на будущее?\n\n\n\n" "### Нужны ли какие-то советы или помощь Клуба?\n\n\n\n" "### Какой совет вы бы сами могли дать идущим по вашим стопам?\n\n", max_length=500000, widget=forms.Textarea( attrs={ "maxlength": 500000, "minlength": 1500, "class": "markdown-editor-full", "data-listen": "keyup", "placeholder": "Расскажите подробности о вашем проекте!" "\n- В чем его суть и как он помогает людям?" "\n- Как появилась идея?" "\n- Какой технический стек вы использовали?" "\n- С какими самыми неожиданными трудностями вы столкнулись?" "\n- Сколько в итоге потратили и заработали?" "\n- Нужны ли какие-то советы или помошь Клуба?" }), ) class Meta: model = Post fields = [ "title", "text", "topic", "url", "image", "is_visible", "is_public" ]
class WebsiteURLForm(forms.Form): url = forms.URLField(max_length=255, verify_exists=False)
class LinkForm(forms.Form): link = forms.URLField() link.widget.attrs.update({ 'class': 'form-control', 'placeholder': "Please enter link"})
class OpenmanageOptsForm(forms.Form): #share_link_ttl = IntervalFormField( # 'D', # label='Share Link Time-to-Live', # initial=datetime.timedelta(minutes=opts['share_link_ttl']) #) if features['ldap']: ad_domain = forms.CharField( required=False, label='Restrict client installs to domain', initial=opts['ad_domain']) autopurge_interval = IntervalFormField( 'D', label='Deleted Items Automatic Purge', initial=datetime.timedelta(days=opts['autopurge_interval']), required=False, ) versionpurge_interval = IntervalFormField( 'D', label='Historical Version Automatic Purge', initial=datetime.timedelta(days=opts['versionpurge_interval']), required=False, ) purgehold_duration = IntervalFormField( 'D', label='Purgehold Duration', initial=datetime.timedelta(seconds=opts['purgehold_duration']), required=False, ) support_email = forms.EmailField(initial=opts['support_email']) admin_email = forms.EmailField(initial=opts['admin_email']) if features['ldap']: omva_url = forms.URLField( label='Management VM External URL', initial=opts['omva_url'], ) timezone = forms.ChoiceField( choices=[(x, x) for x in pytz.common_timezones], initial=file('/etc/timezone').read().strip(), ) def __init__(self, *args, **kwargs): super(OpenmanageOptsForm, self).__init__(*args, **kwargs) if features['ldap']: for var in AGENT_CONFIG_VARS: if var in [ 'send_activation_email', 'resolve_sync_conflicts' ]: if var == 'resolve_sync_conflicts': initial = False help_text = mark_safe( 'Only enable this feature if you have read the documentation ' '<a href="https://spideroak.com/articles/account-page-in-spideroak-enterprise#resolve-sync-conflicts">' 'here.</a>') else: initial = True help_text = '' self.fields[var] = forms.BooleanField( initial=config.get(var, initial), required=False, help_text=help_text, ) else: self.fields[var] = forms.CharField(initial=config.get( var, ''), required=False)
class GoogleRegisterFrom(forms.Form): gog_id = forms.CharField() gog_email = forms.EmailField() gog_full_name = forms.CharField() gog_profile_pic = forms.URLField(required=False)
class SubmitForm(forms.Form): url = forms.URLField(label='Url', max_length=100)
class OAuthApplicationAuthorizationForm(forms.Form): client_id = forms.CharField(max_length=50, widget=forms.HiddenInput()) redirect_uri = forms.URLField(widget=forms.HiddenInput()) state = forms.CharField(max_length=100, widget=forms.HiddenInput(), required=False)
class EditProfileForm(forms.Form): member_id = forms.IntegerField(required=True, min_value=0, widget=forms.HiddenInput) first_name = forms.CharField(max_length=100, required=True) last_name = forms.CharField(max_length=100, required=True) email = forms.EmailField(widget=forms.TextInput(attrs={'size': '50'}), required=True) email2 = forms.EmailField(widget=forms.TextInput(attrs={'size': '50'}), required=False) address1 = forms.CharField(max_length=100, required=False) address2 = forms.CharField(max_length=100, required=False) city = forms.CharField(max_length=100, required=False) state = forms.ChoiceField(choices=STATE_CHOICES, required=False) zipcode = forms.CharField(max_length=5, required=False) phone = forms.CharField(max_length=20, required=False) phone2 = forms.CharField(max_length=20, required=False) company_name = forms.CharField(max_length=100, required=False) url_personal = forms.URLField(required=False) url_professional = forms.URLField(required=False) url_facebook = forms.URLField(required=False) url_twitter = forms.URLField(required=False) url_linkedin = forms.URLField(required=False) url_aboutme = forms.URLField(required=False) url_github = forms.URLField(required=False) gender = forms.ChoiceField(choices=GENDER_CHOICES, required=False) howHeard = forms.ModelChoiceField(label="How heard", queryset=HowHeard.objects.all(), required=False) industry = forms.ModelChoiceField(queryset=Industry.objects.all(), required=False) neighborhood = forms.ModelChoiceField(queryset=Neighborhood.objects.all(), required=False) has_kids = forms.NullBooleanField(required=False) self_employed = forms.NullBooleanField(required=False) emergency_name = forms.CharField( widget=forms.TextInput(attrs={'size': '50'}), label="Name", required=False) emergency_relationship = forms.CharField( widget=forms.TextInput(attrs={'size': '50'}), label="Relationship", required=False) emergency_phone = forms.CharField( widget=forms.TextInput(attrs={'size': '16'}), label="Phone", required=False) emergency_email = forms.EmailField( widget=forms.TextInput(attrs={'size': '50'}), label="E-mail", required=False) def save(self): if not self.is_valid(): raise Exception('The form must be valid in order to save') # Pull the profile to edit member_id = self.cleaned_data['member_id'] profile = Member.objects.get(id=member_id) if not member_id or not profile: raise Exception('Can not find profile to edit') # User data user = profile.user user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] user.save() # Profile data profile.phone = self.cleaned_data['phone'] profile.phone2 = self.cleaned_data['phone2'] profile.email2 = self.cleaned_data['email2'] profile.address1 = self.cleaned_data['address1'] profile.address2 = self.cleaned_data['address2'] profile.city = self.cleaned_data['city'] profile.state = self.cleaned_data['state'] profile.zipcode = self.cleaned_data['zipcode'] profile.url_personal = self.cleaned_data['url_personal'] profile.url_professional = self.cleaned_data['url_professional'] profile.url_facebook = self.cleaned_data['url_facebook'] profile.url_twitter = self.cleaned_data['url_twitter'] profile.url_linkedin = self.cleaned_data['url_linkedin'] profile.url_aboutme = self.cleaned_data['url_aboutme'] profile.url_github = self.cleaned_data['url_github'] profile.gender = self.cleaned_data['gender'] profile.howHeard = self.cleaned_data['howHeard'] profile.industry = self.cleaned_data['industry'] profile.neighborhood = self.cleaned_data['neighborhood'] profile.has_kids = self.cleaned_data['has_kids'] profile.self_emplyed = self.cleaned_data['self_employed'] profile.company_name = self.cleaned_data['company_name'] profile.save() # Emergency Contact data emergency_contact = user.get_emergency_contact() emergency_contact.name = self.cleaned_data['emergency_name'] emergency_contact.relationship = self.cleaned_data[ 'emergency_relationship'] emergency_contact.phone = self.cleaned_data['emergency_phone'] emergency_contact.email = self.cleaned_data['emergency_email'] emergency_contact.save() return profile
class EventSettingsForm(SettingsForm): show_date_to = forms.BooleanField( label=_("Show event end date"), help_text= _("If disabled, only event's start date will be displayed to the public." ), required=False) show_times = forms.BooleanField( label=_("Show dates with time"), help_text= _("If disabled, the event's start and end date will be displayed without the time of day." ), required=False) payment_term_days = forms.IntegerField( label=_('Payment term in days'), help_text= _("The number of days after placing an order the user has to pay to preserve his reservation." ), ) show_items_outside_presale_period = forms.BooleanField( label=_("Show items outside presale period"), help_text= _("Show item details before presale has started and after presale has ended" ), required=False) presale_start_show_date = forms.BooleanField( label=_("Show start date"), help_text=_("Show the presale start date before presale has started"), required=False) payment_term_last = forms.DateTimeField( label=_('Last date of payments'), help_text=_( "The last date any payments are accepted. This has precedence over the number of " "days configured above."), required=False) payment_term_accept_late = forms.BooleanField( label=_('Accept late payments'), help_text= _("Accept payments that come after the end of the order's payment term. " "Payments will only be accepted if the regarding quotas have remaining " "capacity. No payments will be accepted after the 'Last date of payments' " "configured above."), required=False) last_order_modification_date = forms.DateTimeField( label=_('Last date of modifications'), help_text=_( "The last date users can modify details of their orders, such as attendee names or " "answers to questions."), required=False) tax_rate_default = forms.DecimalField( label=_('Tax rate for payment fees'), help_text=_( "The tax rate that applies for additional fees you configured for single payment methods " "(in percent)."), ) timezone = forms.ChoiceField( choices=((a, a) for a in common_timezones), label=_("Default timezone"), ) locales = forms.MultipleChoiceField( choices=settings.LANGUAGES, label=_("Available langauges"), ) locale = forms.ChoiceField( choices=settings.LANGUAGES, label=_("Default language"), ) show_quota_left = forms.BooleanField( label=_("Show number of tickets left"), help_text= _("Publicly show how many tickets of a certain type are still available." ), required=False) attendee_names_asked = forms.BooleanField( label=_("Ask for attendee names"), help_text= _("Ask for a name for all tickets which include admission to the event." ), required=False) attendee_names_required = forms.BooleanField( label=_("Require attendee names"), help_text=_( "Require customers to fill in the names of all attendees."), required=False) invoice_address_asked = forms.BooleanField( label=_("Ask for invoice address"), required=False) invoice_address_required = forms.BooleanField( label=_("Require invoice address"), required=False) invoice_address_vatid = forms.BooleanField( label=_("Ask for VAT ID"), help_text= _("Does only work if an invoice address is asked for. VAT ID is not required." ), required=False) invoice_generate = forms.BooleanField(label=_("Generate invoices"), required=False) invoice_address_from = forms.CharField( widget=forms.Textarea(attrs={'rows': 5}), required=False, label=_("Your address"), help_text=_( "Will be printed as the sender on invoices. Be sure to include relevant details required in " "your jurisdiction (e.g. your VAT ID).")) invoice_additional_text = forms.CharField( widget=forms.Textarea(attrs={'rows': 5}), required=False, label=_("Additional text"), help_text=_( "Will be printed on every invoice below the invoice total.")) invoice_language = forms.ChoiceField( widget=forms.Select, required=True, label=_("Invoice language"), choices=[('__user__', _('The user\'s language'))] + settings.LANGUAGES, ) max_items_per_order = forms.IntegerField( min_value=1, label=_("Maximum number of items per order")) reservation_time = forms.IntegerField( min_value=0, label=_("Reservation period"), help_text= _("The number of minutes the items in a user's card are reserved for this user." ), ) imprint_url = forms.URLField( label=_("Imprint URL"), required=False, ) contact_mail = forms.EmailField( label=_("Contact address"), required=False, help_text=_("Public email address for contacting the organizer")) def clean(self): data = super().clean() if data['locale'] not in data['locales']: raise ValidationError({ 'locale': _('Your default locale must also be enebled for your event (see box above).' ) }) if data['attendee_names_required'] and not data['attendee_names_asked']: raise ValidationError({ 'attendee_names_required': _('You cannot require specifying attendee names if you do not ask for them.' ) }) return data
class S3DirectUploadForm(forms.Form): images = forms.URLField(widget=S3DirectWidget(dest='primary_destination'))
class ProfileForm(forms.Form): website = forms.URLField(max_length=200, required=True) biography = forms.CharField(max_length=500, required=False) phone_number = forms.CharField(max_length=20, required=False) picture = forms.ImageField()
class DocumentForm(forms.Form): name = forms.CharField(max_length=50) link = forms.URLField()
class User_form(forms.Form): link = forms.URLField(max_length=64, label='link to vk profile') expression = forms.CharField(max_length=64, label='any expression (only "+" and "-")')
class ResumeForm(forms.Form): number = forms.IntegerField(validators=[MinValueValidator(1)]) link = forms.URLField() is_latest = forms.BooleanField()
class AddStudyForm(BetterModelForm): name = forms.CharField(label='Study Name', max_length=51) # Study name instrument = forms.ModelChoiceField( queryset=instrument.objects.filter(language='English'), empty_label="(choose from the list)" ) # Study instrument (CANNOT BE CHANGED LATER) demographic = forms.ModelChoiceField( queryset=Demographic.objects.all(), empty_label=_('Default'), required=False) # demographic cannot be changed later waiver = forms.CharField( widget=CKEditorUploadingWidget(), label='Waiver of Documentation text (no titles)', required=False ) # Addition of an IRB waiver of documentation or any other instructive text can be added here allow_payment = forms.BooleanField( required=False, label= "Would you like to pay subjects in the form of Amazon gift cards? (You will need to upload gift card codes under \"Update Study\")." ) # Whether study participants will be compensated in the form of gift card codes upon completion anon_collection = forms.BooleanField( required=False, label= "Do you plan on collecting only anonymous data in this study? (e.g., posting ads on social media, mass emails, etc)" ) # Whether the study will have only anonymous participants (opens up a range of other settings for anonymous data collection) subject_cap = forms.IntegerField( label="Maximum number of participants", required=False, min_value=1, help_text= "Leave this blank if you do NOT want to limit the number of participants.", widget=forms.NumberInput(attrs={'placeholder': 'XXX participants'}) ) # If there are anonymous participants, you can set a cap that limits the number of tests that can be completed. Tests initiated before the cutoff can still be finished even after the cutoff is reached confirm_completion = forms.BooleanField( required=False, label= "At the end of the form, would you like parents to confirm the age of their child and that they completed the entire test? (Best for anonymous data collections where you haven't personally vetted each participant)" ) # Asks participants to verify the child's age and that they completed the form to the best of their ability. Only for participants that have not been vetted. allow_sharing = forms.BooleanField( required=False, label= "Would you like participants to be able to share their Web-CDI results via Facebook?" ) # Gives option for participants to be able to share their results via Facebook. Default off. test_period = forms.IntegerField( label="# Days Before Expiration", help_text= "Between 1 and 28. Default is 14 days. (e.g., 14 = 14 days for parents to complete a form)", required=False, widget=forms.NumberInput( attrs={ 'placeholder': '(e.g., 14 = 14 days to complete a form)', 'min': '1', 'max': '28' }) ) # Number of days that a participant can use to complete an administration before expiration. By default, participants have 14 days to complete test. Ranges from 1-28 days. age_range = IntegerRangeField(label="Age Range For Study (in months)") show_feedback = forms.BooleanField( required=False, initial=True, label= "Would you like to show participants graphs of their data after completion?" ) prefilled_data_choices = ( (0, 'No, do not populate the any part of the form'), (1, 'Only the Background Information Form'), (2, 'The Background Information Form and the Vocabulary Checklist')) prefilled_data = forms.ChoiceField( choices=prefilled_data_choices, label="Pre-fill data for longitudinal participants?", help_text= "For longitudinal participants, would you like to populate the test with responses from earlier tests?" ) birth_weight_choices = (("lb", "Measure birthweight in pounds and ounces"), ("kg", "Measure birthweight in kilograms")) birth_weight_units = forms.ChoiceField( choices=birth_weight_choices, label="Measurement units for birthweight") timing = forms.IntegerField( label= "Minimum time (minutes) a parent must take to complete the study (default=6)", required=True, widget=forms.NumberInput(), initial=6) confirmation_questions = forms.BooleanField( required=False, label= "Would you like participants to answer the confirmation questions (only available when split background information forms are used)" ) redirect_boolean = forms.BooleanField( label="Provide redirect button at completion of study?", required=False ) # Whether to give redirect button upon completion of administration redirect_url = forms.URLField(required=False, help_text="Enter the basic return URL") participant_source_boolean = forms.ChoiceField( label="Participant Source", choices=choices.PARTICIPANT_SOURCE_CHOICES ) # Whether to give redirect button upon completion of administration append_source_id_to_redirect = forms.BooleanField(required=False) source_id_url_parameter_key = forms.CharField(required=False) backpage_boolean = forms.BooleanField( label="Show backpage in split background information study?", required=False) print_my_answers_boolean = forms.BooleanField( label="Allow participant to print their responses at end of Study?", required=False) end_message = forms.ChoiceField(choices=choices.END_MESSAGE_CHOICES) end_message_text = forms.CharField(widget=CKEditorUploadingWidget(), required=False) # Form validation. Form is passed automatically to views.py for higher level checking. def clean(self): cleaned_data = super(AddStudyForm, self).clean() # Initiating form and field layout. def __init__(self, *args, **kwargs): self.researcher = kwargs.pop('researcher', None) super(AddStudyForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'add-study' self.helper.form_class = 'form-horizontal' # self.helper.template = PROJECT_ROOT + '/../cdi_forms/templates/bootstrap3/whole_uni_form.html' # self.helper.template = 'bootstrap4/whole_uni_form.html' self.helper.label_class = 'col-3' self.helper.field_class = 'col-9' self.helper.form_method = 'post' self.fields['backpage_boolean'].initial = True if self.researcher: self.fields['instrument'] = forms.ModelChoiceField( queryset=instrument.objects.filter( researcher=self.researcher.researcher), empty_label="(choose from the list)") self.helper.form_action = reverse('add_study') self.helper.layout = Layout( Field('name'), Field('instrument'), Field('demographic'), Field('age_range'), Field('test_period'), Field('birth_weight_units'), Field('timing'), Field('waiver'), Field('prefilled_data'), Field('allow_payment'), Field('anon_collection'), Field('subject_cap'), Field('confirm_completion'), Field('show_feedback'), Field('allow_sharing'), Field('confirmation_questions'), Fieldset( "Redirect Options", HTML(""" <p>If you would like to connect web-cdi with an external service (e.g., prolific, mturk, lookit), please fill out the following options when applicable</p> """), Field('redirect_boolean', css_class="css_enabler"), Div(Field('redirect_url'), css_class="redirect_boolean collapse"), Field('participant_source_boolean', css_class="css_enabler"), Div(Field('append_source_id_to_redirect'), css_class="participant_source_boolean collapse"), Div(Field('source_id_url_parameter_key'), css_class="participant_source_boolean collapse"), ), Field('backpage_boolean'), Field('print_my_answers_boolean'), Field('end_message'), Field('end_message_text')) # Form is related to the study model. Exclude study group designation (is done post-creation) and researcher name (filled automatically) class Meta: model = study exclude = ['study_group', 'researcher']
class MyForm(forms.ModelForm): url = forms.URLField()
class RenameStudyForm(BetterModelForm): name = forms.CharField(label='Study Name', max_length=51, required=False) # Update study name waiver = forms.CharField(widget=CKEditorUploadingWidget, label='Waiver of Documentation', required=False) test_period = forms.IntegerField( label="# Days Before Expiration", help_text= "Between 1 and 28. Default is 14 days. (e.g., 14 = 14 days for parents to complete a form)", required=False, widget=forms.NumberInput( attrs={ 'placeholder': '(e.g., 14 = 14 days to complete a form)', 'min': '1', 'max': '28' })) # Update testing period. Can range from 1 to 28 days. gift_codes = forms.CharField( widget=forms.Textarea( attrs={ 'placeholder': 'Paste Amazon gift card codes here. Can be separated by spaces, commas, or new lines.' }), required=False, label='Gift Card Codes' ) # Can add a list of gift card codes (separated by new lines, commas, or spaces) to the PaymentCode model that are given out to participants upon completion of current study. gift_amount = forms.CharField( max_length=7, required=False, label="Amount per Card (in USD)", widget=forms.TextInput(attrs={'placeholder': '$XX.XX'}) ) # Specify monetary value of the list of gift card codes in the gift_codes field. Assumed that all codes in the list have the same monetary value. age_range = IntegerRangeField(label="Age Range For Study (in months)") prefilled_data_choices = ( (0, 'No, do not populate the any part of the form'), (1, 'Only the Background Information Form'), (2, 'The Background Information Form and the Vocabulary Checklist')) prefilled_data = forms.ChoiceField( choices=prefilled_data_choices, label="Pre-fill data for longitudinal participants?", help_text= "For longitudinal participants, would you like to populate the test with responses from earlier tests?" ) birth_weight_choices = (("lb", "Measure birthweight in pounds and ounces"), ("kg", "Measure birthweight in kilograms")) birth_weight_units = forms.ChoiceField( choices=birth_weight_choices, label="Measurement units for birthweight") anon_collection = forms.BooleanField( required=False, label= "Do you plan on collecting only anonymous data in this study? (e.g., posting ads on social media, mass emails, etc)" ) # Whether the study will have only anonymous participants (opens up a range of other settings for anonymous data collection) allow_payment = forms.BooleanField( required=False, label= "Would you like to pay subjects in the form of Amazon gift cards? (You will need to upload gift card codes under \"Update Study\")." ) # Whether study participants will be compensated in the form of gift card codes upon completion subject_cap = forms.IntegerField( label="Maximum number of participants", required=False, min_value=1, help_text= "Leave this blank if you do NOT want to limit the number of participants.", widget=forms.NumberInput(attrs={'placeholder': 'XXX participants'}) ) # If there are anonymous participants, you can set a cap that limits the number of tests that can be completed. Tests initiated before the cutoff can still be finished even after the cutoff is reached confirm_completion = forms.BooleanField( required=False, label= "At the end of the form, would you like parents to confirm the age of their child and that they completed the entire test? (Best for anonymous data collections where you haven't personally vetted each participant)" ) # Asks participants to verify the child's age and that they completed the form to the best of their ability. Only for participants that have not been vetted. allow_sharing = forms.BooleanField( required=False, label= "Would you like participants to be able to share their Web-CDI results via Facebook?" ) # Gives option for participants to be able to share their results via Facebook. Default off. show_feedback = forms.BooleanField( required=False, label= "Would you like to show participants graphs of their data after completion?" ) timing = forms.IntegerField( label= "Minimum time (minutes) a parent must take to complete the study (default=6)", required=True) confirmation_questions = forms.BooleanField( required=False, label= "Would you like participants to answer the confirmation questions (only available when split background information forms are used)" ) redirect_boolean = forms.BooleanField( label="Provide redirect button at completion of study?", required=False ) # Whether to give redirect button upon completion of administration redirect_url = forms.URLField( label="Please enter URL", required=False, help_text= "Enter the basic return URL - the Centiment aid will be added automatically" ) participant_source_boolean = forms.ChoiceField( label="Participant Source", choices=choices.PARTICIPANT_SOURCE_CHOICES ) # Whether to give redirect button upon completion of administration backpage_boolean = forms.BooleanField( label="Show backpage in split background information study?", required=False) append_source_id_to_redirect = forms.BooleanField(required=False) source_id_url_parameter_key = forms.CharField(required=False) print_my_answers_boolean = forms.BooleanField( label="Allow participant to print their responses at end of Study?", required=False) end_message = forms.ChoiceField(choices=choices.END_MESSAGE_CHOICES) end_message_text = forms.CharField(widget=CKEditorUploadingWidget(), required=False) # Form validation. Form is passed automatically to views.py for higher level checking. def clean(self): cleaned_data = super(RenameStudyForm, self).clean() # Form initiation. Specific form and field layout. def __init__(self, old_study_name, *args, **kwargs): self.age_range = kwargs.pop('age_range', None) super(RenameStudyForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'rename_study' self.helper.form_class = 'form-horizontal' # self.helper.template = PROJECT_ROOT + '/../cdi_forms/templates/bootstrap3/whole_uni_form.html' self.helper.label_class = 'col-3' self.helper.field_class = 'col-9' self.helper.form_method = 'post' if self.age_range: self.fields['age_range'].initial = self.age_range self.helper.form_action = reverse('rename_study', args=[old_study_name]) self.helper.layout = Layout( Field('name'), Field('age_range'), Field('test_period'), Field('birth_weight_units'), Field('timing'), Field('waiver'), Field('prefilled_data'), Field('anon_collection'), Field('subject_cap'), Field('confirm_completion'), Field('allow_payment'), Div(Field('gift_codes'), css_class="gift_cards collapse"), Div(Field('gift_amount'), css_class="gift_cards collapse"), Field('show_feedback'), Field('allow_sharing'), Field('confirmation_questions'), Fieldset( "Redirect Options", Field('redirect_boolean', css_class="css_enabler"), Div(Field('redirect_url'), css_class="redirect_boolean collapse"), Field('participant_source_boolean', css_class="css_enabler"), Div(Field('append_source_id_to_redirect'), css_class="participant_source_boolean collapse"), Div(Field('source_id_url_parameter_key'), css_class="participant_source_boolean collapse"), ), Field('backpage_boolean'), Field('print_my_answers_boolean'), Field('end_message'), Field('end_message_text')) # Link form to study model. Exclude study group (specified in another form), researcher (automatically filled by current user), and instrument (chosen during study creation and CANNOT BE CHANGED) class Meta: model = study exclude = [ 'study_group', 'researcher', 'instrument', 'active', 'demographic' ]
class SignupForm(forms.Form): displayname = forms.CharField(max_length=80) homepage = forms.URLField(required=False) age = forms.IntegerField(required=False) username = forms.CharField(max_length=80) password = forms.CharField(widget=forms.PasswordInput)
class S3DirectUploadForm(forms.Form): images = forms.URLField(widget=S3DirectWidget(upload_to='images'))