我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.BooleanField()。
def to_python(self, value): """Returns a Python boolean object. It is necessary to customize the behavior because the default ``BooleanField`` treats the string '0' as ``False``, but if the unit is in ``UNTRANSLATED`` state (which would report '0' as a value), we need the marked checkbox to be evaluated as ``True``. :return: ``False`` for any unknown :cls:`~pootle_store.models.Unit` states and for the 'False' string. """ truthy_values = (str(s) for s in (UNTRANSLATED, FUZZY, TRANSLATED)) if (isinstance(value, basestring) and (value.lower() == 'false' or value not in truthy_values)): value = False else: value = bool(value) return super(UnitStateField, self).to_python(value)
def test_create_unbound_form_field_types_1(self): form = PartyForm( 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 'name' in form.fields assert 'project' in form.fields assert 'attrs::dob' in form.fields assert isinstance(form.fields['attrs::dob'], forms.DateField) assert 'attrs::gender' in form.fields assert isinstance(form.fields['attrs::gender'], forms.CharField) assert 'attrs::education' in form.fields assert isinstance(form.fields['attrs::education'], forms.CharField) assert 'attrs::homeowner' in form.fields assert isinstance(form.fields['attrs::homeowner'], forms.BooleanField) assert len(form.fields) == 6
def get_form_field_schema(field): """ Returns the coreapi schema for the given form field. """ title = force_text(field.label) if field.label else '' description = force_text(field.help_text) if field.help_text else '' if isinstance(field, forms.BooleanField): field_class = coreschema.Boolean elif isinstance(field, forms.FloatField): field_class = coreschema.Number elif isinstance(field, (forms.IntegerField, forms.ModelChoiceField)): field_class = coreschema.Integer else: field_class = coreschema.String return field_class(description=description, title=title)
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 make_drawback_form(drawback): class DrawbackForm(forms.Form): def get_label(drawback): requirements = "" required_status = {} for status in HIGH_ROLLER_STATUS: required_status[status[0]] = status[1] if drawback.required_status in [HIGH_ROLLER_STATUS[2][0], HIGH_ROLLER_STATUS[3][0]]: requirements = "requires: {}".format(required_status[drawback.required_status]) return '{} ({}) {}'.format(drawback.name, drawback.description, requirements) label= get_label(drawback) eratta = drawback.eratta drawback_slug=str(drawback.slug) multiplicity_allowed=drawback.multiplicity_allowed; is_selected = forms.BooleanField(required=True) set_field_html_name(is_selected, drawback.form_name()) if drawback.detail_field_label is not "" and drawback.detail_field_label is not None: detail_text = forms.CharField(required=False, label=drawback.detail_field_label) set_field_html_name(detail_text, drawback.form_detail_name()) return DrawbackForm
def test_get_field(self): """ The _get_field method should return a form field instance """ field_1 = self.omniform._get_field('title') field_2 = self.omniform._get_field('agree') field_3 = self.omniform._get_field('fictional') self.assertIsInstance(field_1, forms.CharField) self.assertIsInstance(field_1.widget, forms.TextInput) self.assertEqual(field_1.label, 'Please give us a title') self.assertTrue(field_1.required) self.assertIsInstance(field_2, forms.BooleanField) self.assertIsInstance(field_2.widget, forms.CheckboxInput) self.assertEqual(field_2.label, 'Please agree') self.assertTrue(field_2.required) self.assertIsNone(field_3)
def __init__(self, *args, **kwargs): super(HelpersGiftsForm, self).__init__(*args, **kwargs) if not self.instance.helper.event.ask_shirt: self.fields.pop('got_shirt') self.fields.pop('buy_shirt') for giftset in self.instance.deservedgiftset_set.all(): delivered_id_str = "delivered_{}".format(giftset.pk) self.fields[delivered_id_str] = forms.BooleanField( label=_("Delivered"), required=False, initial=giftset.delivered) for shift in self.instance.helper.shifts.all(): present_id_str = "present_{}".format(shift.pk) self.fields[present_id_str] = forms.BooleanField( label=_("Present"), required=False, initial=self.instance.get_present(shift))
def test_inline_edit_mod_checkbox_with_label(self): class TempTable(MyTable): name = tables.Column(get_name, verbose_name="Verbose Name", sortable=True, form_field=forms.BooleanField( required=True, label="Verbose Name"), form_field_attributes={'class': 'test'}, update_action=MyUpdateAction) class Meta(object): name = "my_table" columns = ('id', 'name', 'value', 'optional', 'status') self.table = TempTable(self.request, TEST_DATA_2) name_col = self.table.columns['name'] name_col.auto = "form_field" row = self.table.get_rows()[0] name_cell = row.cells['name'] name_cell.inline_edit_mod = True # Check if is cell is rendered correctly. name_cell_rendered = name_cell.render() resp = http.HttpResponse(name_cell_rendered) self.assertContains(resp, '<input checked="checked" class="test" ' 'id="name__1" name="name__1" type="checkbox" ' 'value="custom object_1" />', count=1, html=True) self.assertContains(resp, '<label class="inline-edit-label" for="name__1">' 'Verbose Name</label>', count=1, html=True)
def post_process_table(self, field_options): # Add a time selection field fields_add_device_selection(self, keyword='appresponse_device', label='AppResponse', module='appresponse', enabled=True) if self.options.source == 'packets': func = Function(appresponse_source_choices, self.options) TableField.create( keyword='appresponse_source', label='Source', obj=self, field_cls=IDChoiceField, field_kwargs={'widget_attrs': {'class': 'form-control'}}, parent_keywords=['appresponse_device'], dynamic=True, pre_process_func=func ) if self.options.show_entire_pcap: TableField.create(keyword='entire_pcap', obj=self, field_cls=forms.BooleanField, label='Entire PCAP', initial=True, required=False) fields_add_granularity(self, initial=field_options['granularity'], source=self.options.source) fields_add_time_selection(self, show_end=True, initial_duration=field_options['duration'])
def __init__(self, *args, **kwargs): kwargs['blank'] = True super(BooleanField, self).__init__(*args, **kwargs)
def check(self, **kwargs): errors = super(BooleanField, self).check(**kwargs) errors.extend(self._check_null(**kwargs)) return errors
def deconstruct(self): name, path, args, kwargs = super(BooleanField, self).deconstruct() del kwargs['blank'] return name, path, args, kwargs
def get_internal_type(self): return "BooleanField"
def get_prep_lookup(self, lookup_type, value): # Special-case handling for filters coming from a Web request (e.g. the # admin interface). Only works for scalar values (not lists). If you're # passing in a list, you might as well make things the right type when # constructing the list. if value in ('1', '0'): value = bool(int(value)) return super(BooleanField, self).get_prep_lookup(lookup_type, value)
def formfield(self, **kwargs): # Unlike most fields, BooleanField figures out include_blank from # self.null instead of self.blank. if self.choices: include_blank = not (self.has_default() or 'initial' in kwargs) defaults = {'choices': self.get_choices(include_blank=include_blank)} else: defaults = {'form_class': forms.BooleanField} defaults.update(kwargs) return super(BooleanField, self).formfield(**defaults)
def __init__(self, *args, **kwargs): kwargs['required'] = False forms.BooleanField.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['parent'].choices = list(folder_choices()) if self.instance.pk: self.fields['_delete_folder'] = forms.BooleanField( required=False, label=_('Delete this folder'), )
def set_initial(self, args, name, attr, attrvals): if name in attrvals: if attr.attr_type.form_field == 'BooleanField': args['initial'] = ( attrvals[name] if isinstance(attrvals[name], bool) else attrvals[name] != 'False' ) else: args['initial'] = attrvals[name]
def test_create_bound_form_field_types_1(self): party = self.fixtures['party111'] form = PartyForm(instance=party) assert form.attributes_field == 'attrs' assert 'name' in form.fields assert 'project' in form.fields assert 'attrs::dob' in form.fields assert isinstance(form.fields['attrs::dob'], forms.DateField) assert 'attrs::gender' in form.fields assert isinstance(form.fields['attrs::gender'], forms.CharField) assert 'attrs::education' in form.fields assert isinstance(form.fields['attrs::education'], forms.CharField) assert 'attrs::homeowner' in form.fields assert isinstance(form.fields['attrs::homeowner'], forms.BooleanField) assert len(form.fields) == 6
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, user, *args, **kwargs): super().__init__(*args, **kwargs) user_mood_tenses = UserMoodTense.objects.get_mood_tenses_for_user(user) all_mood_tenses = MoodTense.objects.all() for mood_tense in all_mood_tenses: field = forms.BooleanField(initial=mood_tense in user_mood_tenses, label=mood_tense.mood.name + ' ' + mood_tense.tense.name, required=False) field.widget.attrs.update({ 'mood_tense_id': mood_tense.id }) self.fields[str(mood_tense.id)] = field
def test_boolean(self): form_field = forms.BooleanField() core_field = get_form_field_schema(form_field) self.assertTrue(isinstance(core_field, coreschema.Boolean))
def __init__(self, world, *args, **kwargs): super(aidfleetform, self).__init__(*args, **kwargs) query = world.controlled_fleets.all().exclude(sector='warping').exclude(sector='hangar') self.fields['fleetchoice'] = forms.ModelChoiceField(queryset=query) self.fields['retain_control'] = forms.BooleanField(label="Retain ownership")
def __init__(self, *args, **kwargs): vip = kwargs.pop("vip", False) super().__init__(*args, **kwargs) # Are you a VIP? if vip: self.fields["first_class"] = forms.BooleanField( label="Fly First Class?", required=False, initial=True, help_text="First-class only offered to VIPs") self.helper = FormHelper(self) self.helper.layout.append(Submit('submit', 'Submit'))
def __init__(self, *args, **kwargs): super(CardForm, self).__init__(*args, **kwargs) self.previous_member_id = None if self.is_creating else self.instance.member_id self.fields['skill_details'].label = 'Skill details' self.fields['side_skill_details'].label = 'Side skill details' # Delete existing chibis if not self.is_creating: self.all_chibis = self.instance.chibis.all() for imageObject in self.all_chibis: self.fields[u'delete_chibi_{}'.format(imageObject.id)] = forms.BooleanField( label=mark_safe(u'Delete chibi <img src="{}" height="100" />'.format(imageObject.image_url)), initial=False, required=False, )
def __new__(cls, name, bases, attrs): newcls = super().__new__(cls, name, bases, attrs) for row in attrs['layout']: for name in row: if not hasattr(newcls, name): newcls.base_fields[name] = forms.BooleanField(required=False, label=_labels[name]) return newcls
def defaults(self): data = {} for name, field in self.fields.items(): if isinstance(field, forms.BooleanField): data[name] = 'on' return QueryDict(urlencode(data))
def __init__(self, *args, **kwargs): super(RefundForm, self).__init__(*args, **kwargs) this_invoice = kwargs.pop('instance',None) for item in this_invoice.invoiceitem_set.all(): initial = False if item.finalEventRegistration: initial = item.finalEventRegistration.cancelled item_max = item.total + item.taxes if this_invoice.buyerPaysSalesTax else item.total self.fields["item_cancelled_%s" % item.id] = forms.BooleanField( label=_('Cancelled'),required=False,initial=initial) self.fields['item_refundamount_%s' % item.id] = forms.FloatField( label=_('Refund Amount'),required=False,initial=(-1) * item.adjustments, min_value=0, max_value=item_max) self.fields['comments'] = forms.CharField( label=_('Explanation/Comments (optional)'),required=False, help_text=_('This information will be added to the comments on the invoice associated with this refund.'), widget=forms.Textarea(attrs={'placeholder': _('Enter explanation/comments...'), 'class': 'form-control'})) self.fields['id'] = forms.ModelChoiceField( required=True,queryset=Invoice.objects.filter(id=this_invoice.id),widget=forms.HiddenInput(),initial=this_invoice.id) self.fields['initial_refund_amount'] = forms.FloatField( required=True,initial=(-1) * this_invoice.adjustments,min_value=0,max_value=this_invoice.amountPaid + this_invoice.refunds,widget=forms.HiddenInput()) self.fields['total_refund_amount'] = forms.FloatField( required=True,initial=0,min_value=0,max_value=this_invoice.amountPaid + this_invoice.refunds,widget=forms.HiddenInput())
def __init__(self,*args,**kwargs): invoices = kwargs.pop('invoices',Invoice.objects.none()) # Initialize a default (empty) form to fill super(InvoiceNotificationForm, self).__init__(*args, **kwargs) for invoice in invoices: self.fields['invoice_%s' % invoice.id] = forms.BooleanField(label=invoice.id, required=False,initial=True)
def __init__(self, *args, **kwargs): user = kwargs.pop('user',None) # Initialize the default form super(SlotBookingForm, self).__init__(*args, **kwargs) # Allow users with appropriate permissions to process door registrations. if user and user.has_perm('core.accept_door_payments'): self.fields['payAtDoor'] = forms.BooleanField(required=False,label=_('Door/Invoice Registration'))
def __init__(self, is_team_league, round_to_close, round_to_open, season_to_close, *args, **kwargs): super(RoundTransitionForm, self).__init__(*args, **kwargs) if round_to_close is not None: self.fields['complete_round'] = forms.BooleanField(initial=True, required=False, label='Set round %d as completed' % round_to_close.number) self.fields['round_to_close'] = forms.IntegerField(initial=round_to_close.number, widget=forms.HiddenInput) if season_to_close is not None: self.fields['complete_season'] = forms.BooleanField(initial=True, required=False, label='Set %s as completed' % season_to_close.name) if round_to_open is not None: if is_team_league: self.fields['update_board_order'] = forms.BooleanField(initial=True, required=False, label='Update board order') self.fields['generate_pairings'] = forms.BooleanField(initial=True, required=False, label='Generate pairings for round %d' % round_to_open.number) self.fields['round_to_open'] = forms.IntegerField(initial=round_to_open.number, widget=forms.HiddenInput)
def __init__(self, league, player, *args, **kwargs): super(NotificationsForm, self).__init__(*args, **kwargs) for type_, _ in PLAYER_NOTIFICATION_TYPES: setting = PlayerNotificationSetting.get_or_default(player=player, league=league, type=type_) self.fields[type_ + "_lichess"] = forms.BooleanField(required=False, label="Lichess", initial=setting.enable_lichess_mail) self.fields[type_ + "_slack"] = forms.BooleanField(required=False, label="Slack", initial=setting.enable_slack_im) self.fields[type_ + "_slack_wo"] = forms.BooleanField(required=False, label="Slack (with opponent)", initial=setting.enable_slack_mpim) if type_ == 'before_game_time': offset_options = [(5, '5 minutes'), (10, '10 minutes'), (20, '20 minutes'), (30, '30 minutes'), (60, '1 hour'), (120, '2 hours')] self.fields[type_ + '_offset'] = forms.TypedChoiceField(choices=offset_options, initial=int(setting.offset.total_seconds()) / 60, coerce=int)
def get_boolean_value(value): """BooleanField.to_native()""" if value in TRUE_VALUES: return True if value in FALSE_VALUES: return False return bool(value)
def field_from_native(self, data, files, field_name, into): # HTML checkboxes do not explicitly represent unchecked as `False` # we deal with that here... if isinstance(data, QueryDict) and self.default is None: self.default = False return super(BooleanField, self).field_from_native( data, files, field_name, into )
def test_should_boolean_convert_boolean(): field = assert_conversion(forms.BooleanField, graphene.Boolean) assert isinstance(field.type, NonNull)
def prepare_form(self): class MyForm(forms.Form): media_file = forms.FileField(label='??????') if_load = forms.BooleanField(label='??????', required=False)
def get_prep_value(self, value): value = super(BooleanField, self).get_prep_value(value) if value is None: return None return self.to_python(value)
def clean(self): super(PagePermissionInlineAdminForm, self).clean() for field in self.Meta.model._meta.fields: if not isinstance(field, BooleanField) or not field.name.startswith('can_'): continue name = field.name self.cleaned_data[name] = self.cleaned_data.get(name, False) can_add = self.cleaned_data['can_add'] can_edit = self.cleaned_data['can_change'] # check if access for childrens, or descendants is granted if can_add and self.cleaned_data['grant_on'] == ACCESS_PAGE: # this is a missconfiguration - user can add/move page to current # page but after he does this, he will not have permissions to # access this page anymore, so avoid this raise forms.ValidationError(_("Add page permission requires also " "access to children, or descendants, otherwise added page " "can't be changed by its creator.")) if can_add and not can_edit: raise forms.ValidationError(_('Add page permission also requires edit page permission.')) # TODO: finish this, but is it really required? might be nice to have # check if permissions assigned in cms are correct, and display # a message if not - correctness mean: if user has add permission to # page, but he doesn't have auth permissions to add page object, # display warning return self.cleaned_data
def save(self, commit=True): """ Makes sure the boolean fields are set to False if they aren't available in the form. """ instance = super(PagePermissionInlineAdminForm, self).save(commit=False) for field in self._meta.model._meta.fields: if isinstance(field, BooleanField) and field.name.startswith('can_'): setattr(instance, field.name, self.cleaned_data.get(field.name, False)) if commit: instance.save() return instance
def form_field(field): type = models.FormControlType(int(field.control_type)) if (type == models.FormControlType.boolean): return forms.BooleanField(label=field.name) if (type == models.FormControlType.text): return forms.CharField(label=field.name) if (type == models.FormControlType.multiple_choice): choices = map(lambda x: (x, x), field.control_data.split("\n")) return forms.ChoiceField(label=field.name, choices=choices, widget=forms.widgets.SelectMultiple) if (type == models.FormControlType.options): choices = map(lambda x: (x, x), field.control_data.split("\n")) return forms.ChoiceField(label=field.name, choices=choices, widget=forms.widgets.RadioSelect)
def make_enhancement_form(enhancement, enhancement_instance=None): class EnhancementForm(forms.Form): def get_label(enhancement): requirements = "" required_status = {} for status in HIGH_ROLLER_STATUS: required_status[status[0]] = status[1] if enhancement.required_status in [HIGH_ROLLER_STATUS[2][0], HIGH_ROLLER_STATUS[3][0]]: requirements = "requires: {}".format(required_status[enhancement.required_status]) return '{} ({}) {}'.format(enhancement.name, enhancement.description, requirements) label= get_label(enhancement) enhancement_slug=str(enhancement.slug) eratta = enhancement.eratta multiplicity_allowed=enhancement.multiplicity_allowed; is_selected = forms.BooleanField(required=True) if enhancement_instance: is_selected.initial=True set_field_html_name(is_selected, enhancement.form_name()) if enhancement.detail_field_label is not "" and enhancement.detail_field_label is not None: detail_text = forms.CharField(required=False, label=enhancement.detail_field_label) set_field_html_name(detail_text, enhancement.form_detail_name()) if enhancement_instance: detail_text.initial=enhancement_instance.detail return EnhancementForm