我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.ChoiceField()。
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'dest_pool' in self.fields: self.fields['dest_pool'] = forms.ChoiceField( choices=get_pools()) if 'hostgroup' in self.fields: self.fields['hostgroup'].queryset = ( self.fields['hostgroup'].queryset.order_by('name'))
def preferences(request): class NotificationPreferenceForm(forms.ModelForm): event = forms.ChoiceField(choices=registry.get_event_choices(), disabled=True, widget=forms.HiddenInput()) method = forms.ChoiceField(choices=registry.get_method_choices(), disabled=True, widget=forms.HiddenInput()) business_lines = forms.ModelMultipleChoiceField(BusinessLine.authorization.for_user(request.user, 'incidents.view_incidents'), required=False) class Meta: fields = "__all__" formset = forms.inlineformset_factory(User, NotificationPreference, formset=NotificationPreferenceFormset, form=NotificationPreferenceForm) if request.method == 'POST': fs = formset(request.POST, instance=request.user) if fs.is_valid(): fs.save() return redirect('user:profile') else: fs = formset(instance=request.user) return render(request, "fir_async/preferences.html", {'formset': fs})
def __init__(self, world, *args, **kwargs): super(Shipaidform, self).__init__(*args, **kwargs) fleets = fleet.objects.filter((Q(sector=world.sector)|Q(sector='hangar')), world=world, controller=world) techlist = ( ('freighters', 'Freighters'), ('fighters', 'Fighters'), ('corvettes', 'Corvettes'), ('light_cruisers', 'Light Cruisers'), ('destroyers', 'Destroyers'), ('frigates', 'Frigates'), ('heavy_cruisers', 'Heavy Cruisers'), ('battlecruisers', 'Battlecruisers'), ('battleships', 'Battleships'), ('dreadnoughts', 'Dreadnoughts') ) choicelist = [] comparisonfleet = fleet() for ball in fleets: comparisonfleet.merge(ball) for field in techlist: if comparisonfleet.__dict__[field[0]] > 0: choicelist.append(field) choicelist = tuple(choicelist) self.fields["ship_choice"] = forms.ChoiceField(choices=choicelist) self.fields["fleet_choice"] = forms.ModelChoiceField(queryset=fleets)
def __init__(self, *args, **kwargs): questions = sorted(list(kwargs.pop('questions')), key=attrgetter("number")) super(SurveyForm, self).__init__(*args, **kwargs) for i, question in enumerate(questions): if question.type == 'MC': vrs = question.variants self.fields['question_%s' % question.id] = forms.ChoiceField( label=question.text, choices=[(j, vrs[j]) for j in range(len(vrs))], widget=forms.RadioSelect, required=True) elif question.type == 'NR': self.fields['question_%s' % question.id] = forms.ChoiceField( choices=[(i, i) for i in range(1, 11)], label=question.text) elif question.type == 'TE': self.fields['question_%s' % question.id] = forms.CharField( max_length=512, required=True, widget=forms.TextInput(), label=question.text)
def test_create_unbound_form_field_types_2(self): form = ParcelForm( schema_selectors=( {'name': None, 'selector': self.fixtures['org1'].pk}, {'name': 'project', 'value': self.fixtures['proj11'], 'selector': self.fixtures['proj11'].pk} ) ) assert form.attributes_field == 'attrs' assert 'address' in form.fields assert 'project' in form.fields assert 'type' in form.fields assert 'attrs::quality' in form.fields assert 'attrs::infrastructure' in form.fields assert isinstance(form.fields['attrs::quality'], forms.ChoiceField) assert len(form.fields) == 5
def __init__(self, world, *args, **kwargs): super(Blueprinttradeform, self).__init__(*args, **kwargs) offerchoices = [] blueprints = world.blueprints.all() len(blueprints) amounts = [] for tier in v.shipindices[2:]: query = blueprints.filter(model=tier) if len(query) > 0: for blueprint in query: if blueprint.amount not in amounts: amounts.append(blueprint.amount) offerchoices.append((blueprint.pk, blueprint.__str__())) self.fields['offer'] = forms.ChoiceField(choices=offerchoices) self.fields['offer_amount'] = forms.IntegerField(min_value=1, label="Amount", widget=forms.NumberInput( attrs={'size':'10'})) self.fields['amount'] = forms.IntegerField(min_value=1, widget=forms.NumberInput( attrs={'size':'10'})) self.fields['amount'] = forms.IntegerField(min_value=1, widget=forms.NumberInput( attrs={'size':'10'})) self.fields['amount'] = forms.IntegerField(min_value=1, widget=forms.NumberInput( attrs={'size':'10'}))
def __init__(self, *args, **kwargs): reg = kwargs.pop('registration') super(ApproveRegistrationForm, self).__init__(*args, **kwargs) workflow = ApproveRegistrationWorkflow(reg) self.fields['send_confirm_email'].initial = workflow.default_send_confirm_email self.fields['invite_to_slack'].initial = workflow.default_invite_to_slack section_list = reg.season.section_list() if len(section_list) > 1: section_options = [(season.id, season.section.name) for season in section_list] self.fields['section'] = forms.ChoiceField(choices=section_options, initial=workflow.default_section.id) if workflow.is_late: self.fields['retroactive_byes'] = forms.IntegerField(initial=workflow.default_byes) self.fields['late_join_points'] = forms.FloatField(initial=workflow.default_ljp)
def set_choices(self, family): # There's probably a better way of doing this board_choices = [(brd.id, brd.name) for brd in Board.objects.filter(family=family)] self.fields['board_type'].choices = board_choices # class GuidedDeviceFlashForm(forms.Form): # DEVICE_FAMILY_CHOICES = GuidedDeviceSelectForm.DEVICE_FAMILY_CHOICES # # device_family = forms.ChoiceField(label="Device Family", # widget=forms.Select(attrs={'class': 'form-control', # 'data-toggle': 'select'}), # choices=DEVICE_FAMILY_CHOICES, required=True) # should_flash_device = forms.BooleanField(widget=forms.HiddenInput, required=False, initial=False) # #
def get_formfield(model, field): """ Return the formfied associate to the field of the model """ class_field = model._meta.get_field(field) if hasattr(class_field, "field"): formfield = class_field.field.formfield() else: formfield = class_field.formfield() # Otherwise the formfield contain the reverse relation if isinstance(formfield, ChoiceField): formfield.choices = class_field.get_choices() return formfield
def is_update(self): '''Mark all fields not listed in UPDATE_FIELDS as readonly''' for field in self.fields: if not field in self.UPDATE_FIELDS: # DP NOTE: readonly doesn't work for ChoiceFields, as # the user doesn't enter text, but selects a # value. Using a CharField doesn't allow them # to change the drop down, but still see the # selected value if isinstance(self.fields[field], forms.ChoiceField): self.fields[field] = forms.CharField() # DP NOTE: Using disabled means the values are not sent # back to the server, which means if there is a # validation error, the disabled fields will # be empty and also cause validation errors #self.fields[field].disabled = True #self.fields[field].widget.attrs['disabled'] = True self.fields[field].widget.attrs['readonly'] = True return self
def test_new_enterprise_customer(self): """ Test that a new blank form can be created and is not valid. """ self.catalog_api.get_all_catalogs.return_value = [ { "id": self.catalog_id, "name": "My Catalog" }, { "id": 1, "name": "Other catalog!" } ] form = EnterpriseCustomerAdminForm() assert isinstance(form.fields['catalog'], forms.ChoiceField) assert form.fields['catalog'].choices == BLANK_CHOICE_DASH + [ (self.catalog_id, 'My Catalog'), (1, 'Other catalog!'), ] assert not form.is_valid()
def __init__(self, *args, **kwargs): """ Initialize the form. Substitute a ChoiceField in for the catalog field that would normally be set up as a plain number entry field. """ super(EnterpriseCustomerAdminForm, self).__init__(*args, **kwargs) self.fields['catalog'] = forms.ChoiceField( choices=self.get_catalog_options(), required=False, help_text="<a id='catalog-details-link' href='#' target='_blank'" "data-url-template='{catalog_admin_url}'> View catalog details.</a>".format( catalog_admin_url=utils.get_catalog_admin_url_template(), ) )
def get_catalog_options(self): """ Retrieve a list of catalog ID and name pairs. Once retrieved, these name pairs can be used directly as a value for the `choices` argument to a ChoiceField. """ # TODO: We will remove the discovery service catalog implementation # once we have fully migrated customer's to EnterpriseCustomerCatalogs. # For now, this code will prevent an admin from creating a new # EnterpriseCustomer with a discovery service catalog. They will have to first # save the EnterpriseCustomer admin form and then edit the EnterpriseCustomer # to add a discovery service catalog. if hasattr(self.instance, 'site'): catalog_api = CourseCatalogApiClient(self.user, self.instance.site) else: catalog_api = CourseCatalogApiClient(self.user) catalogs = catalog_api.get_all_catalogs() # order catalogs by name. catalogs = sorted(catalogs, key=lambda catalog: catalog.get('name', '').lower()) return BLANK_CHOICE_DASH + [ (catalog['id'], catalog['name'],) for catalog in catalogs ]
def __init__(self, user=None, organisation=None, *args, **kwargs): super().__init__(*args, **kwargs) choices = [(value, string) for value, string in models.RECEIVER_CHOICES if value != models.PLATFORM or (user and user.is_superuser)] self.fields['receivers'] = forms.ChoiceField( label=_('Receivers'), choices=choices, widget=forms.RadioSelect(), ) project_qs = Project.objects if organisation: project_qs = Project.objects.filter(organisation=organisation.id) self.fields['project'] = forms.ModelChoiceField( label=_('Project'), queryset=project_qs, required=False, empty_label=None) self.fields['organisation'] = forms.ModelChoiceField( label=_('Organisation'), queryset=Organisation.objects, required=False, empty_label=None)
def __init__(self, choices, validators, *args, **kwargs): """ :param validators: A dict that maps query type values to validators. """ if validators is None: validators = {} super(MultitypeQueryField, self).__init__(*args, **kwargs) self.fields = ( forms.ChoiceField(choices=choices), forms.CharField(min_length=1) ) self.widget = MultitypeQueryWidget( (forms.Select(choices=choices), forms.TextInput()) ) self.query_validators = validators
def make_default_osystem_field(*args, **kwargs): """Build and return the default_osystem field.""" usable_oses = list_all_usable_osystems() os_choices = list_osystem_choices(usable_oses, include_default=False) if len(os_choices) == 0: os_choices = [('---', '--- No Usable Operating System ---')] field = forms.ChoiceField( initial=Config.objects.get_config('default_osystem'), choices=os_choices, validators=[validate_missing_boot_images], error_messages={ 'invalid_choice': compose_invalid_choice_text( 'osystem', os_choices) }, **kwargs) return field
def make_default_distro_series_field(*args, **kwargs): """Build and return the default_distro_series field.""" default_osystem = Config.objects.get_config('default_osystem') default_usable_os = get_default_usable_osystem(default_osystem) release_choices = [('---', '--- No Usable Release ---')] if default_usable_os is not None: releases = list_all_usable_releases( [default_usable_os])[default_osystem] valid_release_choices = list_choices_for_releases(releases) if len(valid_release_choices) > 0: release_choices = valid_release_choices field = forms.ChoiceField( initial=Config.objects.get_config('default_distro_series'), choices=release_choices, validators=[validate_missing_boot_images], error_messages={ 'invalid_choice': compose_invalid_choice_text( 'release', release_choices) }, **kwargs) return field
def make_default_min_hwe_kernel_field(*args, **kwargs): """Build and return the default_min_hwe_kernel field.""" kernel_choices = [('', '--- No minimum kernel ---')] # Global choices are limited to the commissioning release as min_hwe_kernel # is used during commissioning. commissioning_series = Config.objects.get_config( 'commissioning_distro_series') if commissioning_series: commissioning_os_release = "ubuntu/" + commissioning_series kernel_choices += list_hwe_kernel_choices( [kernel for kernel in BootResource.objects.get_usable_hwe_kernels( commissioning_os_release) if release_a_newer_than_b(kernel, commissioning_series)]) field = forms.ChoiceField( initial=Config.objects.get_config('default_min_hwe_kernel'), choices=kernel_choices, error_messages={ 'invalid_choice': compose_invalid_choice_text( 'default_min_hwe_kernel', kernel_choices) }, **kwargs) return field
def make_commissioning_distro_series_field(*args, **kwargs): """Build and return the commissioning_distro_series field.""" usable_oses = list_all_usable_osystems() commissioning_choices = list_commissioning_choices(usable_oses) if len(commissioning_choices) == 0: commissioning_choices = [('---', '--- No Usable Release ---')] field = forms.ChoiceField( initial=Config.objects.get_config('commissioning_distro_series'), choices=commissioning_choices, validators=[validate_missing_boot_images], error_messages={ 'invalid_choice': compose_invalid_choice_text( 'commissioning_distro_series', commissioning_choices) }, **kwargs) return field
def set_up_architecture_field(self): """Create the `architecture` field. This needs to be done on the fly so that we can pass a dynamic list of usable architectures. """ architectures = list_all_usable_architectures() default_arch = pick_default_architecture(architectures) if len(architectures) == 0: choices = [BLANK_CHOICE] else: choices = list_architecture_choices(architectures) invalid_arch_message = compose_invalid_choice_text( 'architecture', choices) self.fields['architecture'] = forms.ChoiceField( choices=choices, required=False, initial=default_arch, error_messages={'invalid_choice': invalid_arch_message})
def set_up_architecture_field(self): """Create the `architecture` field. This needs to be done on the fly so that we can pass a dynamic list of usable architectures. """ architectures = list_all_usable_architectures() default_arch = pick_default_architecture(architectures) if len(architectures) == 0: choices = [BLANK_CHOICE] else: choices = list_architecture_choices(architectures) invalid_arch_message = compose_invalid_choice_text( 'architecture', choices) self.fields['architecture'] = forms.ChoiceField( choices=choices, required=True, initial=default_arch, error_messages={'invalid_choice': invalid_arch_message})
def test__creates_choice_field_for_choices(self): json_field = { 'name': 'some_field', 'label': 'Some Field', 'field_type': 'choice', 'choices': [ ['choice-one', 'Choice One'], ['choice-two', 'Choice Two'], ], 'default': 'choice-one', 'required': False, } django_field = make_form_field(json_field) self.assertIsInstance(django_field, forms.ChoiceField) self.assertEqual(json_field['choices'], django_field.choices) invalid_msg = compose_invalid_choice_text( json_field['name'], json_field['choices']) self.assertEqual( invalid_msg, django_field.error_messages['invalid_choice']) self.assertEqual(json_field['default'], django_field.initial)
def __init__(self, *args, **kwargs): super(UserPreferencesForm, self).__init__(*args, **kwargs) if not FAVORITE_CHARACTERS: for i in range(1, 4): self.fields.pop('favorite_character{}'.format(i)) else: for i in range(1, 4): self.fields['favorite_character{}'.format(i)] = forms.ChoiceField( required=False, choices=BLANK_CHOICE_DASH + [(name, localized) for (name, localized, image) in FAVORITE_CHARACTERS], label=(_(FAVORITE_CHARACTER_NAME) if FAVORITE_CHARACTER_NAME else _('{nth} Favorite Character')).format(nth=_(ordinalNumber(i)))) self.fields['birthdate'] = date_input(self.fields['birthdate']) if USER_COLORS: self.fields['color'].choices = BLANK_CHOICE_DASH + [(name, localized_name) for (name, localized_name, css_color, hex_color) in USER_COLORS] if self.instance: self.fields['color'].initial = self.instance.color else: self.fields.pop('color') self.fields['language'].choices = [l for l in self.fields['language'].choices if l[0]] self.old_location = self.instance.location if self.instance else None if 'activity' not in RAW_CONTEXT['all_enabled']: del(self.fields['view_activities_language_only'])
def __init__(self, *args, **kwargs): extra = kwargs.pop('extra') super(JobMisClassify, self).__init__(*args, **kwargs) for i, job in enumerate(extra): self.fields['custom_%s' % i] = forms.ChoiceField(label=job, choices=INDUSTRY_CHOICES, required=False) # self.fields['custom_%s' % i] = forms.CharField(label=job, max_length=250, required=False)
def extra_answers(self): for name, value in self.cleaned_data.items(): if name.startswith('custom_'): yield (self.fields[name].label, value) # super(EducationMisClassify, self).__init__(*args, **kwargs) # for i in range(0, n): # self.fields["edu_correct %d" % i] = forms.ChoiceField(choices=MISCLASSIFY_SELECTION,) # edu_correct = forms.CharField(max_length=250)
def __init__(self, *args, **kwargs): super(VPOSTypeForm, self).__init__(*args, **kwargs) if hasattr(settings, "ENABLED_VPOS_LIST") and settings.ENABLED_VPOS_LIST: vpos_types = settings.ENABLED_VPOS_LIST else: vpos_types = VPOS_TYPES self.fields["type"] = forms.ChoiceField(choices=vpos_types, required=True, label="Tipo de TPV", help_text="Tipo de pasarela de pago a crear.")
def vars_for_template(self): """Sets variables for template: Question form and additional data""" # create question form form = _UnderstandingQuestionsForm() # add questions to form questions = self.get_questions() for q_idx, q_def in enumerate(questions): answer_field = forms.ChoiceField(label=q_def['question'], choices=_choices_for_field(q_def['options'])) correct_val_field = forms.CharField(initial=q_def['correct'], widget=forms.HiddenInput) hint_field = forms.CharField(initial=q_def.get('hint', self.default_hint), widget=forms.HiddenInput) form.add_field('q_input_%d' % q_idx, answer_field) form.add_field('q_correct_%d' % q_idx, correct_val_field) form.add_field('q_hint_%d' % q_idx, hint_field) # optionally add field with number of wrong attempts if self.form_model and self.form_field_n_wrong_attempts: form.add_field(self.form_field_n_wrong_attempts, forms.CharField(initial=0, widget=forms.HiddenInput)) return { 'questions_form': form, 'n_questions': len(questions), 'hint_empty': self.default_hint_empty, 'form_field_n_wrong_attempts': self.form_field_n_wrong_attempts or '', 'set_correct_answers': str(self.set_correct_answers).lower(), }
def __init__(self, *args, **kwargs): product_classes = kwargs.pop('product_classes', []) super(ProductClassSelectorForm, self).__init__(*args, **kwargs) choices = [(obj.pk, obj.name) for obj in product_classes] self.fields['product_cls'] = forms.ChoiceField( label=pgettext_lazy('Product class form label', 'Product type'), choices=choices, widget=forms.RadioSelect)
def __init__(self, *args, **kwargs): super(ReviewForm, self).__init__(*args, **kwargs) self.fields["vote"] = forms.ChoiceField( widget=forms.RadioSelect(), choices=VOTES.CHOICES )
def make_reorder_languagelist_form(objlist): choices = [(e.id, e.ascii_name) for e in objlist] class ReorderLanguageListForm(forms.Form): language = forms.ChoiceField( choices=choices, widget=forms.Select(attrs={"size": 20})) return ReorderLanguageListForm
def make_reorder_meaninglist_form(objlist): choices = [(e.id, e.gloss) for e in objlist] class ReorderMeaningListForm(forms.Form): meaning = forms.ChoiceField( choices=choices, widget=forms.Select(attrs={"size": 20})) return ReorderMeaningListForm
def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'widget_type': widgets = widget_manager.get_widgets(self.request.GET.get('page_id', '')) form_widget = WidgetTypeSelect(widgets) return forms.ChoiceField(choices=[(w.widget_type, w.description) for w in widgets], widget=form_widget, label=_('Widget Type')) if 'page_id' in self.request.GET and db_field.name == 'page_id': kwargs['widget'] = forms.HiddenInput field = super( UserWidgetAdmin, self).formfield_for_dbfield(db_field, **kwargs) return field
def __init__(self, required=True, widget=None, label=None, initial=None, help_text=None, *args, **kwargs): # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). forms.Field.__init__(self, required, widget, label, initial, help_text, *args, **kwargs) self.widget.choices = self.choices
def choice_field(self, **kwargs): if self.hidden: kwargs['widget'] = forms.MultipleHiddenInput() return forms.ChoiceField(choices=self.choices, **kwargs)
def test_model_field(self): """ The 'model_field' field should be defined """ field = self.form.fields['model_field'] self.assertIsInstance(field, forms.ChoiceField) self.assertEqual(field.label, 'Field') self.assertEqual(set(field.choices), set(self.generator_1.all_attributes.items()))
def __init__(self, choices, *args, **kwargs): fields = [ forms.ChoiceField(choices=choices, widget=forms.RadioSelect, required=False), forms.CharField(required=False, widget=forms.TextInput, help_text='Other') ] self.widget = OptionalChoiceWidget(widgets=[f.widget for f in fields]) super().__init__(required=False, fields=fields, *args, **kwargs)
def test_create_bound_form_field_types_2(self): parcel = self.fixtures['parcel111'] form = ParcelForm(instance=parcel) assert form.attributes_field == 'attrs' assert 'address' in form.fields assert 'project' in form.fields assert 'type' in form.fields assert 'attrs::quality' in form.fields assert 'attrs::infrastructure' in form.fields assert isinstance(form.fields['attrs::quality'], forms.ChoiceField) assert len(form.fields) == 5 labels = [ch[1] for ch in form.fields['attrs::quality'].choices] assert 'None' in labels assert 'Textual' in labels print(labels)
def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') super().__init__(*args, **kwargs) self.fields['divdept'] = forms.ChoiceField( label='Division/Department', choices=choices )
def __init__(self, *args, **kwargs): super(SelectNetworkForm, self).__init__(*args, **kwargs) # We create the choice field here in the init so that if the network # values change, the form will pick up the changes and not require the # server to be restarted. choices = [] all_networks = models.Network.objects.all() for network in all_networks: value = network.id try: user_profile = models.UserProfile.objects.get(network=network) except models.UserProfile.DoesNotExist: continue if user_profile.user.email: owner = user_profile.user.email else: owner = user_profile.user.username display = '%s (%s)' % (network.name, owner) choices.append((value, display)) self.fields['network'] = forms.ChoiceField( label="Network", choices=choices, required=False) # Set layout attributes. self.helper = FormHelper() self.helper.form_id = 'select-network-form' self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Select')) self.helper.layout = Layout('network')
def __init__(self, *args, **kwargs): super(SelectTowerForm, self).__init__(*args, **kwargs) # We create the choice field here in the init so that if the network # values change, the form will pick up the changes and not require the # server to be restarted. choices = [] # We create a convoluted tower queryset so that towers that have never # synced (last_active = None) sort after active and inactive towers. the_past = datetime.datetime.now() - datetime.timedelta(days=10*365) all_towers = models.BTS.objects.all().annotate( new_last_active=Coalesce('last_active', Value(the_past))).order_by( '-new_last_active') for tower in all_towers: value = tower.id user_profile = models.UserProfile.objects.get( network=tower.network) abbreviated_uuid = tower.uuid[0:5] if tower.nickname: prefix = 'Tower "%s" - %s..' % ( tower.nickname, abbreviated_uuid) else: prefix = 'Tower %s..' % abbreviated_uuid display = '%s (%s)' % (prefix, user_profile.user.email) choices.append((value, display)) self.fields['tower'] = forms.ChoiceField( label="Tower", choices=choices, required=False) # Set layout attributes. self.helper = FormHelper() self.helper.form_id = 'select-tower-form' self.helper.form_method = 'post' self.helper.form_action = '/dashboard/staff/tower-monitoring' self.helper.add_input(Submit('submit', 'Select')) self.helper.layout = Layout('tower')
def test_fields(self): """ This tests that all fields were added to the form with the correct types """ form_class = self.fb.get_form_class() field_names = form_class.base_fields.keys() # All fields are present in form self.assertIn('your-name', field_names) self.assertIn('your-biography', field_names) self.assertIn('your-birthday', field_names) self.assertIn('your-birthtime', field_names) self.assertIn('your-email', field_names) self.assertIn('your-homepage', field_names) self.assertIn('your-favourite-number', field_names) self.assertIn('your-favourite-python-ides', field_names) self.assertIn('your-favourite-python-ide', field_names) self.assertIn('your-choices', field_names) self.assertIn('i-agree-to-the-terms-of-use', field_names) # All fields have proper type self.assertIsInstance(form_class.base_fields['your-name'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-biography'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-birthday'], forms.DateField) self.assertIsInstance(form_class.base_fields['your-birthtime'], forms.DateTimeField) self.assertIsInstance(form_class.base_fields['your-email'], forms.EmailField) self.assertIsInstance(form_class.base_fields['your-homepage'], forms.URLField) self.assertIsInstance(form_class.base_fields['your-favourite-number'], forms.DecimalField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ides'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-choices'], forms.MultipleChoiceField) self.assertIsInstance(form_class.base_fields['i-agree-to-the-terms-of-use'], forms.BooleanField) # Some fields have non-default widgets self.assertIsInstance(form_class.base_fields['your-biography'].widget, forms.Textarea) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'].widget, forms.RadioSelect) self.assertIsInstance(form_class.base_fields['your-choices'].widget, forms.CheckboxSelectMultiple)
def __init__(self, event, user, *args, instance=None, **kwargs): self.event = event self.may_override = event.settings.allow_override_votes and user.remaining_override_votes(event) self.may_override = self.may_override or (instance and instance.override_vote is not None) self.min_value = int(event.settings.review_min_score) self.max_value = int(event.settings.review_max_score) if instance: if instance.override_vote is True: instance.score = self.max_value + 1 elif instance.override_vote is False: instance.score = self.min_value - 1 super().__init__(*args, instance=instance, **kwargs) choices = [(None, _('No score'))] if self.may_override: choices.append((self.min_value - 1, _('Negative override (Veto)'))) for counter in range(abs(self.max_value - self.min_value) + 1): value = self.min_value + counter name = event.settings.get(f'review_score_name_{value}') if name: name = f'{value} (»{name}«)' else: name = value choices.append((value, name)) if self.may_override: choices.append((self.max_value + 1, _('Positive override'))) self.fields['score'] = forms.ChoiceField(choices=choices, required=False, disabled=kwargs.get('read_only', False)) self.fields['text'].widget.attrs['rows'] = 2 self.fields['text'].widget.attrs['placeholder'] = phrases.orga.example_review