class ServiceCreateForm(forms.ModelForm): """ """ target_audience = forms.TypedMultipleChoiceField( choices=constants.TARGET_AUDIENCE_CHOICES, widget=HorizontalCheckboxSelectMultiple(), help_text=Service._meta.get_field("target_audience").help_text, ) support_access = forms.TypedMultipleChoiceField( choices=constants.SUPPORT_ACCESS_CHOICES, widget=HorizontalCheckboxSelectMultiple(), help_text=Service._meta.get_field("support_access").help_text, ) support_mode = forms.TypedMultipleChoiceField( choices=constants.SUPPORT_MODE_CHOICES, widget=HorizontalCheckboxSelectMultiple(), help_text=Service._meta.get_field("support_mode").help_text, ) def __init__(self, *args, **kwargs): super(ServiceCreateForm, self).__init__(*args, **kwargs) # set readonly fields # for fieldname in Service.AUTO_POPULATED_FIELDS: # self.fields[fieldname].widget.attrs["readonly"] = True class Meta: model = Service exclude = []
class SettingsForm(forms.Form): # start_list = forms.TypedMultipleChoiceField(choices=lists.Lists) start_list = forms.TypedMultipleChoiceField() start_list.widget.attrs.update({'class': 'custom-select my-1 mr-2'}) key_words = forms.CharField(required=False) key_words.widget.attrs.update({'class': 'form-control'}) # labels = forms.TypedMultipleChoiceField(choices=lists.Labels) labels = forms.TypedMultipleChoiceField() labels.widget.attrs.update({'class': 'custom-select my-1 mr-2'}) # executors = forms.TypedMultipleChoiceField(choices=lists.Members) executors = forms.TypedMultipleChoiceField() executors.widget.attrs.update({'class': 'custom-select my-1 mr-2'}) attachment = forms.BooleanField(required=False) attachment.widget.attrs.update({'class': 'form-check-input'}) comments = forms.BooleanField(required=False) comments.widget.attrs.update({'class': 'form-check-input'}) from_date = None to_date = None due_date = None def __init__(self, lists=[], labels=[], members=[], *args, **kwargs): super(SettingsForm, self).__init__(*args, **kwargs) self.fields['start_list'].choices = lists self.fields['labels'].choices = labels self.fields['executors'].choices = members
def __init__(self, db_pool, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-addExperimentForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = '' self.helper.add_input(Submit('submit', 'Submit')) choices = [] with get_users(db_pool) as csr: for id, fname, lname, dept, _, _, role in csr: choices.append((id, "%s %s %s at %s" % (fname, lname, role, dept))) self.fields['researchers'] = forms.TypedMultipleChoiceField( label='Researchers', choices = tuple(choices), required=True, widget=forms.SelectMultiple(attrs={'size' : 20}) ) choices= [] with get_tools(db_pool) as csr: for id, manufacturer, mname, _, _ in csr: choices.append((id, "%s %s" % (manufacturer, mname))) self.fields['tools'] = forms.TypedMultipleChoiceField( label='Tools', choices = tuple(choices), required=True, widget=forms.SelectMultiple(attrs={'size' : 10}) )
class NewAddonForm(AddonUploadForm): desktop_platforms = forms.TypedMultipleChoiceField( choices=amo.DESKTOP_PLATFORMS_CHOICES, widget=forms.CheckboxSelectMultiple(attrs={'class': 'platform'}), initial=[amo.PLATFORM_ALL.id], required=False, coerce=int) mobile_platforms = forms.TypedMultipleChoiceField( choices=amo.MOBILE_PLATFORMS_CHOICES, widget=forms.CheckboxSelectMultiple(attrs={'class': 'platform'}), required=False, coerce=int) def clean(self): if not self.errors: self._clean_upload() xpi = parse_addon(self.cleaned_data['upload']) addons.forms.clean_name(xpi['name']) self._clean_all_platforms() return self.cleaned_data def _clean_all_platforms(self): if (not self.cleaned_data['desktop_platforms'] and not self.cleaned_data['mobile_platforms']): raise forms.ValidationError(_('Need at least one platform.'))
class VerticalForm(InlineForm): failure_message = "Failed to complete operation" success_message = "Successfully completed the operation" CHOICES = ((1, "One"), (2, "Two"), (3, "Three"), (4, "Four"), (5, "Five"), (6, "Six")) name = forms.CharField(max_length=100) avatar = forms.ImageField() attachment = forms.FileField() # boolean_with_switch = forms.BooleanField(initial=False, help_text="Some useless advice", widget=SwitchInput) boolean_with_checkbox = forms.BooleanField(initial=False, help_text="Some useless advice") choices_with_radio = forms.TypedChoiceField(coerce=int, choices=CHOICES, widget=forms.RadioSelect) choices_with_select = forms.TypedChoiceField(coerce=int, choices=CHOICES, widget=forms.Select) multiple_choices_with_select = forms.TypedMultipleChoiceField( coerce=int, choices=CHOICES, widget=forms.SelectMultiple) multiple_choices_with_checkbox = forms.TypedMultipleChoiceField( coerce=int, choices=CHOICES, widget=forms.CheckboxSelectMultiple) age = forms.IntegerField() textarea = forms.CharField(widget=forms.Textarea, help_text="Text area is a good thing") date = forms.DateField() time = forms.TimeField() datetime = forms.DateTimeField()
class EmailForm(forms.Form): """ Form to gather recipients, subject and message for sending email announcements """ error_css_class = 'field-error' required_css_class = 'field-required' # Define these as None just so I can order them everyone = forms.BooleanField(required=False, label='All Users') experimenters = forms.TypedMultipleChoiceField( required=False, coerce=int, label='Users' ) groups = forms.TypedMultipleChoiceField( required=False, coerce=int ) # TODO CC isn't really CC. Maybe change label or change functionality cc = MultiEmailField(required=False) subject = forms.CharField(max_length=100, required=True) message = forms.CharField(widget=Textarea, required=True) # Include/Exclude inactive users inactive = forms.BooleanField(label='Include inactive users', required=False) def __init__(self, experimenters, groups, conn, request, *args, **kwargs): super(EmailForm, self).__init__(*args, **kwargs) # Process Experimenters/Groups into choices (lists of tuples) self.fields['experimenters'].choices = [ (experimenter.id, experimenter.firstName + ' ' + experimenter.lastName + ' (' + experimenter.omeName + ')' + (' - Inactive' if not experimenter.isActive() else '')) for experimenter in experimenters] self.fields['groups'].choices = [ (group.id, group.name) for group in groups] self.conn = conn self.request = request def clean(self): cleaned_data = super(EmailForm, self).clean() everyone = cleaned_data.get("everyone") experimenters = cleaned_data.get("experimenters") groups = cleaned_data.get("groups") cc = cleaned_data.get("cc") # If nobody addressed, throw an error if not cc and not everyone and not experimenters and not groups: raise forms.ValidationError("At least one addressee must be " "specified in one or more of 'all'," " 'user', 'group' or 'cc'") return cleaned_data
class FilterForm(forms.Form): category = forms.TypedMultipleChoiceField( label='Category', help_text="Select one or more category") status = forms.TypedChoiceField(label='Status', help_text="Select status") link_type = forms.TypedChoiceField(label='Type', help_text="Select type") client = forms.TypedMultipleChoiceField( label='Client', help_text="Select one or more client") date_from = forms.DateField(label='From', help_text='Select from date') date_to = forms.DateField(label='To', help_text='Select to date')
class SubmissionCreateAndReviewForm(SubmissionReviewForm): STUDENT_FIELDS = ('students', 'students_by_user_id', 'students_by_student_id', 'students_by_email') submission_time = forms.DateTimeField() students = forms.ModelMultipleChoiceField( queryset=UserProfile.objects.none(), required=False) students_by_user_id = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda user_id: User.objects.get(id=user_id).userprofile, choices=[], required=False) students_by_student_id = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda student_id: UserProfile.get_by_student_id(student_id), choices=[], required=False) students_by_email = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda email: UserProfile.get_by_email(email), choices=[], required=False) def __init__(self, *args, **kwargs): super(SubmissionCreateAndReviewForm, self).__init__(*args, **kwargs) self.fields["students"].queryset = \ UserProfile.objects.all() self.fields["students_by_user_id"].choices = \ [ (p.user_id, p) for p in UserProfile.objects.all() ] self.fields["students_by_student_id"].choices = \ [ (p.student_id, p.student_id) for p in UserProfile.objects.all() ] self.fields["students_by_email"].choices = \ [ (u.email, u.email) for u in User.objects.all() ] def clean(self): self.cleaned_data = data = super(SubmissionCreateAndReviewForm, self).clean() fields = self.STUDENT_FIELDS n = sum((1 if data.get(k) else 0) for k in fields) if n == 0: raise forms.ValidationError( _("One of the student fields must not be blank")) if n > 1: raise forms.ValidationError( _("Only one student field can be given")) return data @property def cleaned_students(self): data = self.cleaned_data for field in self.STUDENT_FIELDS: s = data.get(field) if s: return s raise RuntimeError("Didn't find any students")
class CheckboxSelectMultipleForm(forms.Form): description = "CheckboxSelectMultiple options" CHOICES = ((1, 'Apple'), (2, 'Orange'), (3, 'Watermeloun')) field1 = forms.MultipleChoiceField(help_text='default', choices=CHOICES, widget=forms.CheckboxSelectMultiple) field2 = forms.MultipleChoiceField(help_text='initial value', choices=CHOICES, widget=forms.CheckboxSelectMultiple, initial=[2, 3]) field3 = forms.TypedMultipleChoiceField( help_text='cource to int', choices=CHOICES, widget=forms.CheckboxSelectMultiple, coerce=int) field4 = forms.ModelMultipleChoiceField( help_text='model multichoice with to_field_name=codename, 2 columns', widget=forms.CheckboxSelectMultiple, queryset=Permission.objects.filter( content_type__app_label__in=['auth', 'frontend']), to_field_name='codename') field5 = forms.MultipleChoiceField(help_text='default', choices=CHOICES, widget=forms.CheckboxSelectMultiple, disabled=True, required=False) template = Template(""" {% form %} {% part form.field4 columns %}2{% endpart %} {% endform %} """)
class MultipleChoiceFieldForm(forms.Form): description = "MultipleChoiceField options" CHOICES = ((None, 'Select a fruit'), (1, 'Apple'), (2, 'Orange'), (3, 'Watermeloun')) FLOAT_CHOICES = ( (1.1, 'Perfect'), (1.0, 'Good'), (0.8, 'Bad'), ) LONG_CHOICES = ((n, n) for n in range(100)) field1 = forms.MultipleChoiceField(help_text='default', choices=CHOICES) field2 = forms.MultipleChoiceField(help_text='initial value', choices=CHOICES, initial=[2, 3]) field3 = forms.MultipleChoiceField(help_text='float choices', choices=FLOAT_CHOICES) field4 = forms.MultipleChoiceField(help_text='long choices list', choices=LONG_CHOICES) field5 = forms.TypedMultipleChoiceField(help_text='cource to int', coerce=int, choices=CHOICES) field6 = forms.MultipleChoiceField(help_text='prefix', choices=CHOICES) field7 = forms.MultipleChoiceField(help_text='disabled', choices=CHOICES, initial=[2, 3], disabled=True, required=False) template = Template(""" {% form %} {% part form.field6 prefix %}<i class="material-icons prefix">insert_invitation</i>{% endpart %} {% endform %} """)
class SearchBansForm(Form): ban = forms.CharField(required=False) reason = forms.CharField(required=False) test = forms.TypedMultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=((0, _('Username and e-mail')), (1, _('Username')), (2, _('E-mail address')), (3, _('IP Address'))), coerce=int, required=False) layout = (( _("Search Bans"), ( ('ban', { 'label': _("Ban"), 'attrs': { 'placeholder': _("Ban contains...") } }), ('reason', { 'label': _("Messages"), 'attrs': { 'placeholder': _("User or Team message contains...") } }), ('test', { 'label': _("Type") }), ), ), )
class GameSearchForm(forms.Form): title = forms.CharField(required=False) category = forms.TypedMultipleChoiceField( required=False, choices=[] ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].widget.attrs = { 'class': 'form-control flex-fill mr-0 mr-sm-2 mb-3 mb-sm-0 col-xs-4 col-md-6', 'placeholder': 'Search by game title' } self.fields['category'].widget.attrs = { 'class': 'selectpicker form-control flex-fill mr-0 mr-sm-2 mb-3 mb-sm-0 col-xs-4 col-md-3 categories-align', 'data-live-search-normalize': 'true', 'data-live-search': 'true', 'data-container': 'body', 'data-header': 'Categories', 'max-options-text': 'All', 'title': 'Select categories' } categories_choices = [ (category['slug'], category['title']) for category in Category.objects.values('title', 'slug') ] self.fields['category'].choices = categories_choices
class UpdateForm(forms.Form): gedcom_id = forms.IntegerField() gedcom_file = forms.FileField( label='Select a file', help_text='Max file size: 42M.' ) email_users = forms.TypedMultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=[(a, str(a)) for a in range(100)] # TODO: Unhack ) message = forms.CharField(required=False) def is_valid(self): if not super(UpdateForm, self).is_valid(): self.error_message = 'Please upload a valid gedcom file.' return False data = self.cleaned_data self.gedcom = get_object_or_404(Gedcom, id=data['gedcom_id']) for id_ in data['email_users']: get_object_or_404(User, pk=id_) if data['email_users'] and not data['message']: self.error_message = 'You must enter a message if emailing users.' return False return True
class NewAddonForm(AddonUploadForm): supported_platforms = forms.TypedMultipleChoiceField( choices=amo.SUPPORTED_PLATFORMS_CHOICES, widget=forms.CheckboxSelectMultiple(attrs={'class': 'platform'}), initial=[amo.PLATFORM_ALL.id], coerce=int, error_messages={'required': 'Need at least one platform.'}) is_unlisted = forms.BooleanField( initial=False, required=False, label=_lazy(u'Do not list my add-on on this site (beta)'), help_text=_lazy( u'Check this option if you intend to distribute your add-on on ' u'your own and only need it to be signed by Mozilla.')) is_sideload = forms.BooleanField( initial=False, required=False, label=_lazy(u'This add-on will be side-loaded via application ' u'installers.'), help_text=_lazy(u'Add-ons that are side-loaded will be code reviewed ' u'by Mozilla before they are signed and are held to a ' u'higher quality standard.')) def clean(self): if not self.errors: self._clean_upload() xpi = parse_addon(self.cleaned_data['upload']) # We don't enforce name uniqueness for unlisted add-ons. if not self.cleaned_data.get('is_unlisted', False): addons.forms.clean_name(xpi['name'], addon_type=xpi['type']) return self.cleaned_data
class DeviceTypeForm(forms.Form): device_types = forms.TypedMultipleChoiceField( choices=[(k, v.name) for k, v in amo.DEVICE_TYPES.items()], coerce=int, initial=amo.DEVICE_TYPES.keys(), widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): self.addon = kwargs.pop('addon') super(DeviceTypeForm, self).__init__(*args, **kwargs) device_types = AddonDeviceType.objects.filter( addon=self.addon).values_list('device_type', flat=True) if device_types: self.initial['device_types'] = device_types def save(self, addon): new_types = self.cleaned_data['device_types'] old_types = [x.id for x in addon.device_types] added_devices = set(new_types) - set(old_types) removed_devices = set(old_types) - set(new_types) for d in added_devices: addon.addondevicetype_set.create(device_type=d) for d in removed_devices: addon.addondevicetype_set.filter(device_type=d).delete() # Send app to re-review queue if public and new devices are added. if added_devices and self.addon.status in amo.WEBAPPS_APPROVED_STATUSES: mark_for_rereview(self.addon, added_devices, removed_devices)
class ILBForm(forms.Form): course = forms.CharField(label=u'Ausbildungsabschnitt', max_length=60) year = forms.TypedChoiceField(label=u'Ausbildungsjahr', coerce=int, choices=[(x, unicode(x)) for x in xrange(1, 5)]) start = forms.DateField( label=_(u'Kursanfang'), input_formats=['%Y-%m-%d', '%m/%d/%Y', '%d.%m.%Y', '%d.%m.%y']) end = forms.DateField( label=_(u'Kursende'), input_formats=['%Y-%m-%d', '%m/%d/%Y', '%d.%m.%Y', '%d.%m.%y']) students = forms.TypedMultipleChoiceField( label=u'Azubis', choices=get_students(), coerce=int, widget=forms.SelectMultiple(attrs={'size': '18'})) school1 = forms.TypedChoiceField(choices=WEEKDAYS, coerce=int, required=False, empty_value=None) school2 = forms.TypedChoiceField(choices=WEEKDAYS, coerce=int, required=False, empty_value=None)
class UserEdit(UserChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields['password'] phone_hidden_fields = forms.BooleanField(label='Скрыть номер', required=False) email_hidden_fields = forms.BooleanField(label='Скрыть email', required=False) prime_time_fields = forms.MultipleChoiceField( label='Прайм-тайм', required=False, choices=[(c.pk, c.prime_time) for c in UserPrimeTime.objects.all()], widget=CheckboxSelectMultiple) activity_fields = forms.TypedMultipleChoiceField( label='Активности', required=False, choices=[(c.pk, c.activity) for c in UserActivity.objects.all()], widget=CheckboxSelectMultiple) role_fields = forms.MultipleChoiceField( label='Роли', required=False, choices=[(c.pk, c.role_name) for c in UserRole.objects.all()], widget=CheckboxSelectMultiple) class Meta: model = get_user_model() fields = ('first_name', 'email', 'timezone', 'phone', 'city')
class DeviceTypeForm(forms.Form): device_types = forms.TypedMultipleChoiceField( choices=[(k, v.name) for k, v in amo.DEVICE_TYPES.items()], coerce=int, label=_lazy(u'Which device types does your app work with?'), initial=amo.DEVICE_TYPES.keys(), widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): self.addon = kwargs.pop('addon') super(DeviceTypeForm, self).__init__(*args, **kwargs) device_types = AddonDeviceType.objects.filter( addon=self.addon).values_list('device_type', flat=True) if device_types: self.initial['device_types'] = device_types def save(self, addon): new_types = self.cleaned_data['device_types'] old_types = [x.id for x in addon.device_types] # Add new AddonDeviceTypes. for d in set(new_types) - set(old_types): AddonDeviceType(addon=addon, device_type=d).save() # Remove old AddonDeviceTypes. for d in set(old_types) - set(new_types): AddonDeviceType.objects.filter(addon=addon, device_type=d).delete()
class TestForm(forms.Form): a_charfield = forms.CharField(help_text='Any string') a_textarea = forms.CharField(widget=forms.Textarea, help_text='Any paragraph') url = forms.URLField() a_boolean = forms.BooleanField() select_option = forms.ChoiceField(choices=CHOICES) a_date = forms.DateField() a_datetime = forms.DateTimeField() a_decimal = forms.DecimalField() an_email = forms.EmailField() a_file = forms.FileField() #a_filepath = forms.FilePathField() a_float = forms.FloatField() an_image = forms.ImageField() an_integer = forms.IntegerField() an_ipaddress = forms.IPAddressField() #a_generic_ipaddress = forms.GenericIPAddressField() a_multiple_choice = forms.MultipleChoiceField(choices=CHOICES) a_typed_multiple_choice = forms.TypedMultipleChoiceField(choices=CHOICES) a_null_boolean = forms.NullBooleanField() #not sure what this should be a_regex = forms.RegexField( regex=r'<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>') #matches tags a_slug = forms.SlugField() a_time = forms.TimeField()
class ManyFieldsExampleForm(forms.Form): hiddeninput = forms.CharField(widget=forms.HiddenInput()) multiplehiddeninput = forms.MultipleChoiceField(widget=forms.MultipleHiddenInput, choices=CONTINENTS) modelchoicefield = forms.ModelChoiceField(queryset=Friend.objects.all(), empty_label="Empty Space", to_field_name="first_name") modelchoicefield2 = forms.ModelChoiceField(queryset=Friend.objects.all(), to_field_name="first_name") modelmultiplechoicefield = forms.ModelMultipleChoiceField(queryset=Friend.objects.all()) booleanfield = forms.BooleanField(label="BooleanField") charfield = forms.CharField(label="CharField") choicefield = forms.ChoiceField(label="ChoiceField", choices=CONTINENTS) typedchoicefield = forms.TypedChoiceField(label="TypedChoiceField") datefield = forms.DateField(label="DateField") datetimefield = forms.DateTimeField(label="DateTimeField") decimalfield = forms.DecimalField(label="DecimalField") durationfield = forms.DurationField(label="DurationField") emailfield = forms.EmailField(label="EmailField") filefield = forms.FileField(label="FileField") filepathfield = forms.FilePathField(label="FilePathField", path="/") floatfield = forms.FloatField(label="FloatField") imagefield = forms.ImageField(label="ImageField") integerfield = forms.IntegerField(label="IntegerField") genericipaddressfield = forms.GenericIPAddressField(label="GenericIPAddressField") multiplechoicefield = forms.MultipleChoiceField(label="MultipleChoiceField", choices=CONTINENTS) typedmultiplechoicefield = forms.TypedMultipleChoiceField(label="TypedMultipleChoiceField", choices=CONTINENTS) nullbooleanfield = forms.NullBooleanField(label="NullBooleanField") slugfield = forms.SlugField(label="SlugField") timefield = forms.TimeField(label="TimeField") urlfield = forms.URLField(label="URLField") uuidfield = forms.UUIDField(label="UUIDField")
def __init__(self, *args, **kwargs): blog_id = kwargs.pop('blog_id') blog = Blog.objects.get(id=blog_id) super(EditBlogInvites, self).__init__(*args, **kwargs) data = tuple([(x.id, x.user.username) for x in blog.invites.all()]) self.fields['invites'] = forms.TypedMultipleChoiceField( choices=data, required=False, widget=forms.CheckboxSelectMultiple)
class ProjectProgressFilter(FilterForm): """ Implements a filter on I4pProjectTranslation progression """ progress = forms.TypedMultipleChoiceField( required=False, coerce=str, choices=I4pProjectTranslation.PROGRESS_CHOICES, widget=MyCheckboxSelectMultiple) def apply_to(self, queryset, model_class): qs = queryset if model_class == I4pProjectTranslation: data = self.cleaned_data.get("progress") if data: q_objects = None for val in data: lookup = {"completion_progress": val} if q_objects: q_objects |= Q(**lookup) else: q_objects = Q(**lookup) qs = qs.filter(q_objects) return qs def __init__(self, *args, **kwargs): super(FilterForm, self).__init__(*args, **kwargs) self.fields['progress'].widget.attrs['class'] = 'styled'
def __init__(self, *args, **kwargs): metrics = kwargs.pop('metrics') entities = kwargs.pop('entities') sources = kwargs.pop('sources') data_centers = kwargs.pop('data_centers') hashtags = kwargs.pop('hashtags') urls = kwargs.pop('urls') super(TwitterUsersForm, self).__init__(*args, **kwargs) # TODO maybe SplitDateTimeField ? self.fields['start_date'] = forms.DateTimeField(required=False, help_text='Optional') self.fields['end_date'] = forms.DateTimeField(required=False, help_text='Optional') self.fields['metrics'] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=metrics) self.fields['entities'] = forms.ModelMultipleChoiceField( queryset=entities) self.fields['entities'].initial = entities self.fields['sources'] = forms.ModelMultipleChoiceField( queryset=sources) self.fields['sources'].initial = sources self.fields['data_centers'] = forms.TypedMultipleChoiceField( choices=data_centers, coerce=int) self.fields['data_centers'].initial = [d[0] for d in data_centers] self.fields['hashtags'] = forms.ModelMultipleChoiceField( queryset=hashtags, required=False, help_text='leave blank to ignore filter') self.fields['urls'] = forms.ModelMultipleChoiceField( queryset=urls, required=False, help_text='leave blank to ignore filter') self.fields['action'] = forms.ChoiceField(choices=self.ACTIONS_CHOICES, required=True)
class NewVersionForm(AddonUploadForm): supported_platforms = forms.TypedMultipleChoiceField( choices=amo.SUPPORTED_PLATFORMS_CHOICES, widget=forms.CheckboxSelectMultiple(attrs={'class': 'platform'}), initial=[amo.PLATFORM_ALL.id], coerce=int, error_messages={'required': 'Need at least one platform.'}) beta = forms.BooleanField( required=False, help_text=_lazy(u'A file with a version ending with ' u'a|alpha|b|beta|pre|rc and an optional number is ' u'detected as beta.')) def __init__(self, *args, **kw): self.addon = kw.pop('addon', None) super(NewVersionForm, self).__init__(*args, **kw) def clean(self): if not self.errors: self._clean_upload() xpi = parse_addon(self.cleaned_data['upload'], self.addon) # Make sure we don't already have the same non-rejected version. version_exists = self.addon and Version.unfiltered.filter( addon=self.addon, version=xpi['version']).exists() if version_exists: msg = _(u'Version %s already exists, or was uploaded before.') raise forms.ValidationError(msg % xpi['version']) return self.cleaned_data
class SubmissionCreateAndReviewForm(SubmissionReviewForm): submission_time = forms.DateTimeField() students = forms.ModelMultipleChoiceField( queryset=UserProfile.objects.none(), required=False) students_by_student_id = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda student_id: UserProfile.get_by_student_id(student_id), choices=[(p.student_id, p.student_id) for p in UserProfile.objects.none()], required=False) students_by_email = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda email: UserProfile.get_by_email(email), choices=[(u.email, u.email) for u in User.objects.none()], required=False) def __init__(self, *args, **kwargs): super(SubmissionCreateAndReviewForm, self).__init__(*args, **kwargs) self.fields["students"].queryset = \ UserProfile.objects.all() #self.exercise.course_instance.get_student_profiles() self.fields["students_by_student_id"].choices = \ [ (p.student_id, p.student_id) for p in UserProfile.objects.all() #self.exercise.course_instance.get_student_profiles() ] self.fields["students_by_email"].choices = \ [ (u.email, u.email) for u in User.objects.all() ] def clean(self): self.cleaned_data = super(SubmissionCreateAndReviewForm, self).clean() n = 0 if self.cleaned_data.get("students"): n += 1 if self.cleaned_data.get("students_by_student_id"): n += 1 if self.cleaned_data.get("students_by_email"): n += 1 if n == 0: raise forms.ValidationError( _("One of the student fields must not be blank: students, students_by_student_id, students_by_email" )) if n > 1: raise forms.ValidationError( _("Only one student field can be given: students, students_by_student_id, students_by_email" )) return self.cleaned_data
class UserSearchForm(forms.Form): TOT_CHOICES = ( ('rental', 'Аренда'), ('purchase', 'Покупка'), ) type_of_transaction = forms.MultipleChoiceField(choices=TOT_CHOICES, required=False, widget=forms.widgets.CheckboxSelectMultiple, label='Вид сделки') N_CHOICES = ( ('new_building', 'Новостройка'), ('secondary', 'Вторичка'), ) novelty = forms.MultipleChoiceField(choices=N_CHOICES, required=False, widget=forms.widgets.CheckboxSelectMultiple, label='Новизна квартиры') NOR_CHOICES = ( ('0', 'Студия'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6+'), ) number_of_rooms = forms.TypedMultipleChoiceField(choices=NOR_CHOICES, coerce=int, required=False, widget=forms.widgets.CheckboxSelectMultiple, label='Колличество комнат') price_from = forms.IntegerField(required=False, label='Цена от (в руб.)') price_up_to = forms.IntegerField(required=False, label='Цена до (в руб.)') D_CHOICES = ( ('Admiralteyskiy', 'Адмиралтейский'), ('Vasileostrovskiy', 'Василеостровский'), ('Vyborgskiy', 'Выборгский'), ('Kalininskiy', 'Калининский'), ('Kirovsky', 'Кировский'), ('Kolpinsky', 'Колпинский'), ('Krasnogvardeisky', 'Красногвардейский'), ('Krasnoselsky', 'Красносельский'), ('Kronshtadtskiy', 'Кронштадтский'), ('Kurortnyy', 'Курортный'), ('Moskovskiy', 'Московский'), ('Nevsky', 'Невский'), ('Petrogradsky', 'Петроградский'), ('Petrodvortsovyy', 'Петродворцовый'), ('Primorskiy', 'Приморский'), ('Pushkinskiy', 'Пушкинский'), ('Frunzenskiy', 'Фрунзенский'), ('Tsentralnyy', 'Центральный'), ) district = forms.MultipleChoiceField(choices=D_CHOICES, required=False, widget=forms.widgets.CheckboxSelectMultiple, label='Район') def clean(self): super().clean() errors = {} if self.cleaned_data['price_from']: if self.cleaned_data['price_from'] < 0: errors['price_from'] = ValidationError('Цена не может быть отрицательной') if self.cleaned_data['price_up_to']: if self.cleaned_data['price_up_to'] < 0: errors['price_up_to'] = ValidationError('Цена не может быть отрицательной') if self.cleaned_data['price_up_to'] and self.cleaned_data['price_from']: if self.cleaned_data['price_up_to'] < self.cleaned_data['price_from']: errors['price_up_to'] = ValidationError('Цена "до" не может быть меньше цены "от"') if errors: raise ValidationError(errors)
class FormularioUsuarioPersona(FormularioPersona): ''' Formulario para el alta de un nuevo usuario de una persona dentro del sistema ''' NAME = 'usuario_persona_form' SUBMIT = 'usuario_persona_submit' usuario = forms.CharField() password = forms.CharField() ''' gruposEmp = set() valor = 1 for g in Group.objects.all(): e = Group.objects.select_related().get(id=valor) if str(e) != 'propietario' and str(e) != 'profesional': gruposEmp.add((str(valor), str(e))) valor += 1 grupo = forms.TypedMultipleChoiceField(gruposEmp) ''' gruposEmp = {('1', 'director'), ('2', 'administrativo'), ('3', 'visador'), ('4', 'inspector'), ('7', 'jefeinspector')} grupo = forms.TypedMultipleChoiceField(gruposEmp) def __init__(self, *args, **kwargs): super(FormularioUsuarioPersona, self).__init__(*args, **kwargs) self.fields['usuario'].widget.attrs[ 'placeholder'] = "Ingresar Nombre Usuario" self.fields['usuario'].widget.attrs['pattern'] = ".{5,}" self.fields['password'].widget.attrs[ 'placeholder'] = "Ingresar Contrasena" self.fields['password'].widget.attrs['pattern'] = ".{6,}" self.fields['usuario'].widget.attrs['title'] = "Ingresar Usuario" self.fields['password'].widget.attrs['title'] = "Ingresar Contrasena" def save(self, commit=False): ''' Funcion save: Funcion para guardar un usuario persona :param self, commit: self: commit indica si se debe guardar, self es referencia al objeto :return usuario: instancia de usuario. ''' persona = super(FormularioUsuarioPersona, self).save(commit=False) datos = self.cleaned_data persona.usuario = Usuario.objects.create_user( username=datos['usuario'], email=datos['mail'], password=datos['password'], ) grupo_post = datos['grupo'] for g in self.gruposEmp: for gp in grupo_post: if g[0] == gp: persona.usuario.save() persona.save() usuario = persona.usuario usuario.groups.add(gp) '''return usuario'''
class ReviewAppForm(happyforms.Form): comments = forms.CharField(widget=forms.Textarea(), label=_lazy(u'Comments:')) canned_response = NonValidatingChoiceField(required=False) action = forms.ChoiceField(widget=forms.RadioSelect()) device_types = forms.CharField(required=False, label=_lazy(u'Device Types:')) browsers = forms.CharField(required=False, label=_lazy(u'Browsers:')) device_override = forms.TypedMultipleChoiceField( choices=[(k, v.name) for k, v in amo.DEVICE_TYPES.items()], coerce=int, label=_lazy(u'Device Type Override:'), widget=forms.CheckboxSelectMultiple, required=False) notify = forms.BooleanField(required=False, label=_lazy( u'Notify me the next time the manifest is ' u'updated. (Subsequent updates will not ' u'generate an email)')) def __init__(self, *args, **kw): self.helper = kw.pop('helper') self.type = kw.pop('type', amo.CANNED_RESPONSE_APP) super(ReviewAppForm, self).__init__(*args, **kw) # We're starting with an empty one, which will be hidden via CSS. canned_choices = [['', [('', _('Choose a canned response...'))]]] responses = CannedResponse.objects.filter(type=self.type) # Loop through the actions. for k, action in self.helper.actions.iteritems(): action_choices = [[c.response, c.name] for c in responses if c.sort_group and k in c.sort_group.split(',')] # Add the group of responses to the canned_choices array. if action_choices: canned_choices.append([action['label'], action_choices]) # Now, add everything not in a group. for r in responses: if not r.sort_group: canned_choices.append([r.response, r.name]) self.fields['canned_response'].choices = canned_choices self.fields['action'].choices = [ (k, v['label']) for k, v in self.helper.actions.items() ] device_types = AddonDeviceType.objects.filter( addon=self.helper.addon).values_list('device_type', flat=True) if device_types: self.initial['device_override'] = device_types def is_valid(self): result = super(ReviewAppForm, self).is_valid() if result: self.helper.set_data(self.cleaned_data) return result
def __init__(self, queryDict, *args, **kwargs): languages = kwargs.pop('languages') sign_languages = kwargs.pop('sign_languages') dialects = kwargs.pop('dialects') language_code = kwargs.pop('language_code') super(MorphemeSearchForm, self).__init__(queryDict, *args, **kwargs) for language in languages: morphemesearch_field_name = self.morpheme_search_field_prefix + language.language_code_2char setattr( self, morphemesearch_field_name, forms.CharField(label=_("Gloss") + (" (%s)" % language.name))) if morphemesearch_field_name in queryDict: getattr(self, morphemesearch_field_name ).value = queryDict[morphemesearch_field_name] # do the same for Translations keyword_field_name = self.keyword_search_field_prefix + language.language_code_2char setattr( self, keyword_field_name, forms.CharField(label=_("Translations") + (" (%s)" % language.name))) if keyword_field_name in queryDict: getattr( self, keyword_field_name).value = queryDict[keyword_field_name] field_label_signlanguage = gettext("Sign language") field_label_dialects = gettext("Dialect") self.fields['SIGNLANG'] = forms.ModelMultipleChoiceField( label=field_label_signlanguage, widget=Select2, queryset=SignLanguage.objects.filter( id__in=[signlanguage[0] for signlanguage in sign_languages])) self.fields['dialects'] = forms.ModelMultipleChoiceField( label=field_label_dialects, widget=Select2, queryset=Dialect.objects.filter( id__in=[dia[0] for dia in dialects])) field_language = language_code for fieldname in settings.MULTIPLE_SELECT_MORPHEME_FIELDS: field_label = self.Meta.model._meta.get_field( fieldname).verbose_name field_category = fieldname_to_category(fieldname) field_choices = FieldChoice.objects.filter( field__iexact=field_category) translated_choices = choicelist_queryset_to_translated_dict( field_choices, field_language, ordered=False, id_prefix='', shortlist=True) self.fields[fieldname] = forms.TypedMultipleChoiceField( label=field_label, choices=translated_choices, required=False, widget=Select2)
def __init__(self, *args, **kwargs): blog_topics = kwargs.pop('blog_topics') super(EditBlogTopics, self).__init__(*args, **kwargs) topics_unselect = tuple([ (x.id, x.name) for x in Topic.objects.all() if x.name != "Personal" and x not in blog_topics.all() ]) topics_select = tuple([(x.id, x.name) for x in blog_topics.all() if x.name != "Personal"]) self.fields['topics_unselect'] = forms.TypedMultipleChoiceField( choices=topics_unselect, required=False, widget=forms.CheckboxSelectMultiple) self.fields['topics_select'] = forms.TypedMultipleChoiceField( choices=topics_select, required=False, widget=forms.CheckboxSelectMultiple)