我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.IntegerField()。
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 __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, world, *args, **kwargs): super(Aidform, self).__init__(*args, **kwargs) reslist = ( ('budget', 'GEU'), ('warpfuel', 'Warpfuel'), ('duranium', 'Duranium'), ('tritanium', 'Tritanium'), ('adamantium', 'Adamantium') ) choicelist = [] for field in reslist: if world.__dict__[field[0]] > 0: #if resource count > 0 choicelist.append(field) #this gives is hella dynamic forms #django loves tuples, so for resource in choicelist: max_number = world.__dict__[resource[0]] self.fields[resource[0]] = forms.IntegerField(widget=forms.NumberInput( attrs={'size':'10'}), label="%s: " % resource[1], min_value=0, max_value=max_number)
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 clean(self): cleaned_data = super(AppAddForm, self).clean() app_id = forms.IntegerField(required=True) app_name = cleaned_data.get('app_name') app_domain = cleaned_data.get('app_domain') app_manager = cleaned_data.get('app_manager') app_callback = cleaned_data.get('app_callback') if not app_name: self._errors['app_name'] = self.error_class([u"???????"]) if not app_domain: self._errors['app_domain'] = self.error_class([u"???????"]) if not app_manager: self._errors['app_manager'] = self.error_class([u"???????"]) if not app_callback: self._errors['app_callback'] = self.error_class([u"???????"]) if not app_id: self._errors['app_id'] = self.error_class([u"???????"]) return cleaned_data
def clean(self): cleaned_data = super(PolicyAddForm, self).clean() # policy_id = forms.IntegerField(required=False) policy_name = cleaned_data.get('policy_name') policy_active = cleaned_data.get('policy_active') policy_default = cleaned_data.get('policy_default') policy_desc = cleaned_data.get('policy_desc') if not policy_name: self._errors['policy_name'] = self.error_class([u"???????"]) if not policy_active: self._errors['policy_active'] = self.error_class([u"???????"]) # if not policy_id: # self._errors['policy_id'] = self.error_class([u"???????"]) if not policy_default: self._errors['policy_default'] = self.error_class([u"???????"]) if not policy_desc: self._errors['policy_desc'] = self.error_class([u"???????"]) return cleaned_data
def clean(self): cleaned_data = super(PolicyEditForm, self).clean() policy_id = forms.IntegerField(required=True) policy_name = cleaned_data.get('policy_name') policy_active = cleaned_data.get('policy_active') policy_default = cleaned_data.get('policy_default') policy_desc = cleaned_data.get('policy_desc') if not policy_name: self._errors['policy_name'] = self.error_class([u"???????"]) if not policy_active: self._errors['policy_active'] = self.error_class([u"???????"]) if not policy_id: self._errors['policy_id'] = self.error_class([u"???????"]) if not policy_default: self._errors['policy_default'] = self.error_class([u"???????"]) if not policy_desc: self._errors['policy_desc'] = self.error_class([u"???????"]) return cleaned_data
def clean(self): cleaned_data = super(PolicyForm, self).clean() policy_id = forms.IntegerField(required=True) policy_name = cleaned_data.get('policy_name') policy_active = cleaned_data.get('policy_active') policy_default = cleaned_data.get('policy_default') policy_desc = cleaned_data.get('policy_desc') if not policy_name: self._errors['policy_name'] = self.error_class([u"???????"]) if not policy_active: self._errors['policy_active'] = self.error_class([u"???????"]) if not policy_id: self._errors['policy_id'] = self.error_class([u"???????"]) if not policy_default: self._errors['policy_default'] = self.error_class([u"???????"]) if not policy_desc: self._errors['policy_desc'] = self.error_class([u"???????"]) return cleaned_data
def validators(self): # These validators can't be added at field initialization time since # they're based on values retrieved from `connection`. validators_ = super(IntegerField, self).validators internal_type = self.get_internal_type() min_value, max_value = connection.ops.integer_field_range(internal_type) if min_value is not None: for validator in validators_: if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value: break else: validators_.append(validators.MinValueValidator(min_value)) if max_value is not None: for validator in validators_: if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value: break else: validators_.append(validators.MaxValueValidator(max_value)) return validators_
def __init__(self, *args, **kwargs): workshop = kwargs.pop('workshop') discount_code = kwargs.pop('discount_code') super().__init__(*args, **kwargs) self.rate_set = workshop.filter_rates(discount_code) for rate in self.rate_set: self.fields[rate.name] = forms.IntegerField( initial=0, min_value=0, max_value=rate.capacity - rate.ticket_count, widget=forms.NumberInput(attrs={'class': 'form-control'}) ) for rate in workshop.sold_out_rates.all(): self.fields[rate.name] = forms.IntegerField( initial=0, min_value=0, disabled=True, widget=forms.NumberInput(attrs={'class': 'form-control'}) )
def add_port(self, port_name, direct_port, proxy_port, hostname): direct_field = forms.IntegerField(label=port_name + ' directly to port', initial=direct_port, min_value=1, max_value=2**16-1, required=False) self.fields[self.get_direct_field_name(port_name)] = direct_field proxy_field = forms.IntegerField(label=port_name + ' via reverse proxy to port', initial=proxy_port, min_value=1, max_value=2**16-1, required=False) self.fields[self.get_proxy_field_name(port_name)] = proxy_field hostname_field = forms.CharField(label=port_name + ' hostname ', initial=hostname, max_length=100, required=False) self.fields[self.get_hostname_field_name(port_name)] = hostname_field
def remove(request, link_id): ''' Remove a specific link with ID ``link_id`` ''' from django.forms import IntegerField from django.forms import ValidationError field = IntegerField(min_value=1) try: value = field.clean(link_id) except ValidationError as err: jd = json.dumps({'rc': 1, 'response': '\n'.join(err.messages)}) return HttpJSONResponseBadRequest(content=jd) try: LinkReference.unlink(value) except Exception as err: jd = json.dumps({'rc': 1, 'response': str(err)}) return HttpJSONResponseBadRequest(content=jd) return HttpJSONResponse( content=json.dumps( {'rc': 0, 'response': 'Link has been removed successfully.'}))
def set_fields(cls, category, products): for product in products: if product.description: help_text = "$%d each -- %s" % ( product.price, product.description, ) else: help_text = "$%d each" % product.price field = forms.IntegerField( label=product.name, help_text=help_text, min_value=0, max_value=500, # Issue #19. We should figure out real limit. ) cls.base_fields[cls.field_name(product)] = field
def set_fields(cls, category, products): choices = [] if not category.required: choices.append((0, "---")) for product in products: choice_text = "%s -- $%d each" % (product.name, product.price) choices.append((product.id, choice_text)) cls.base_fields[cls.CHOICE_FIELD] = forms.TypedChoiceField( label=category.name, widget=forms.Select, choices=choices, initial=0, empty_value=0, coerce=int, ) cls.base_fields[cls.QUANTITY_FIELD] = forms.IntegerField( label="Quantity", # TODO: internationalise min_value=0, max_value=500, # Issue #19. We should figure out real limit. )
def staff_products_form_factory(user): ''' Creates a StaffProductsForm that restricts the available products to those that are available to a user. ''' products = inventory.Product.objects.all() products = ProductController.available_products(user, products=products) product_ids = [product.id for product in products] product_set = inventory.Product.objects.filter(id__in=product_ids) class StaffProductsForm(forms.Form): ''' Form for allowing staff to add an item to a user's cart. ''' product = forms.ModelChoiceField( widget=forms.Select, queryset=product_set, ) quantity = forms.IntegerField( min_value=0, ) return StaffProductsForm
def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super(GiftSetForm, self).__init__(*args, **kwargs) available_gifts = Gift.objects.filter(event=self.event) self.gift_form_ids = {} for gift in available_gifts: id = "gift_{}".format(gift.pk) self.gift_form_ids[gift.pk] = id number = 0 if self.instance: number = self.instance.get_gift_num(gift) self.fields[id] = forms.IntegerField(label=gift.name, required=False, min_value=0, initial=number)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for profile in Member.profile_classes: for field in profile._meta.fields: if field.name not in ('id', 'member'): self.fields[f'{profile.__name__}__{field.name}'] = forms.IntegerField(required=False, label=f'{field.verbose_name or field.name} ({profile.__name__})') config = Configuration.get_solo().registration_form or [] for entry in config: field = self.fields.get(entry['name']) if field: field.initial = entry['position']
def test_populate(self): """Create a FormsetDataTable and populate it with data.""" class TableForm(forms.Form): name = forms.CharField() value = forms.IntegerField() TableFormset = forms.formsets.formset_factory(TableForm, extra=0) class Table(table_formset.FormsetDataTable): formset_class = TableFormset name = tables.Column('name') value = tables.Column('value') class Meta(object): name = 'table' table = Table(self.request) table.data = TEST_DATA_4 formset = table.get_formset() self.assertEqual(2, len(formset)) form = formset[0] form_data = form.initial self.assertEqual('object_1', form_data['name']) self.assertEqual(2, form_data['value'])
def check(self, **kwargs): errors = super(IntegerField, self).check(**kwargs) errors.extend(self._check_max_length_warning()) return errors
def _check_max_length_warning(self): if self.max_length is not None: return [ checks.Warning( "'max_length' is ignored when used with IntegerField", hint="Remove 'max_length' from field", obj=self, id='fields.W122', ) ] return []
def validators(self): # These validators can't be added at field initialization time since # they're based on values retrieved from `connection`. range_validators = [] internal_type = self.get_internal_type() min_value, max_value = connection.ops.integer_field_range(internal_type) if min_value is not None: range_validators.append(validators.MinValueValidator(min_value)) if max_value is not None: range_validators.append(validators.MaxValueValidator(max_value)) return super(IntegerField, self).validators + range_validators
def get_prep_value(self, value): value = super(IntegerField, self).get_prep_value(value) if value is None: return None return int(value)
def get_prep_lookup(self, lookup_type, value): if ((lookup_type == 'gte' or lookup_type == 'lt') and isinstance(value, float)): value = math.ceil(value) return super(IntegerField, self).get_prep_lookup(lookup_type, value)
def formfield(self, **kwargs): defaults = {'form_class': forms.IntegerField} defaults.update(kwargs) return super(IntegerField, self).formfield(**defaults)
def __init__(self, *args, **kwargs): kwargs['required'] = False forms.IntegerField.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): kwargs['required'] = False kwargs['min_value'] = 0 forms.IntegerField.__init__(self, *args, **kwargs)
def test_overridden_form_class(self): """ Tests type of form returned by BitOptionsField.formfield when default form_class parameter is overridden. """ f = BitOptionsField() form = f.formfield(form_class=IntegerField) self.assertTrue(isinstance(form, IntegerField))
def __init__(self, conf, *args, **kwargs): super(BaseRobokassaForm, self).__init__(*args, **kwargs) self.conf = conf # IsTest field self.fields['IsTest'] = forms.IntegerField(initial=1 if self.conf.TEST_MODE else 0) # ??????? ?????????????? ???? for key in self.conf.EXTRA_PARAMS: self.fields['shp'+key] = forms.CharField(required=False) if 'initial' in kwargs: self.fields['shp'+key].initial = kwargs['initial'].get(key, 'None')
def __init__(self, *args, **kwargs): nb_questions = kwargs.pop('nb_questions') super(AddQuestionForm, self).__init__(*args, **kwargs) self.fields['question'] = forms.IntegerField( required=True, validators=[MinValueValidator(1), MaxValueValidator(nb_questions + 1)]) self.fields['question'].label = 'Question number' self.fields['question'].help_text = ('(value between 1 and %s)' % (nb_questions + 1))
def __init__(self, *args, **kwargs): nb_questions = kwargs.pop('nb_questions') super(RemoveQuestionForm, self).__init__(*args, **kwargs) self.fields['question'] = forms.IntegerField( required=True, validators=[MinValueValidator(1), MaxValueValidator(nb_questions)]) self.fields['question'].label = 'Question number' self.fields['question'].help_text = ('(value between 1 and %s)' % (nb_questions))
def test_integer(self): form_field = forms.IntegerField() core_field = get_form_field_schema(form_field) self.assertTrue(isinstance(core_field, coreschema.Integer)) self.assertTrue(core_field.integer_only)
def __init__(self, world, *args, **kwargs): super(Shiptradeform, self).__init__(*args, **kwargs) fleets = fleet.objects.filter(Q(sector=world.sector)|Q(sector='hangar'), world=world, controller=world) choices = [] for tier in v.shipindices: for f in fleets: if f.__dict__[tier] > 0: choices.append((tier, tier.replace('_', ' ').capitalize())) break exclusionlist = [] for f in fleets: if f.power() == 0: exclusionlist.append(f.pk) for f in exclusionlist: fleets = fleets.exclude(pk=f) choices = tuple(choices) self.fields['offer'] = forms.ChoiceField(choices=choices, label="Ship type") self.fields['fleet'] = forms.ModelChoiceField(queryset=fleets, label="From") self.fields['offer_amount'] = forms.IntegerField(min_value=1, label="Amount", widget=forms.NumberInput( attrs={'size':'10'})) self.fields['request'] = forms.ChoiceField(choices=RESOURCE_CHOICES) self.fields['request_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'})) #request = forms.ChoiceField(choices=RESOURCE_CHOICES) #request_amount = forms.IntegerField(min_value=1) #amount = forms.IntegerField(min_value=1)
def __init__(self, world, *args, **kwargs): super(Resourcetradeform, self).__init__(*args, **kwargs) offerchoices = [] for item in RESOURCE_CHOICES: if world.__dict__[item[0]] > 0: offerchoices.append(item) self.fields['offer'] = forms.ChoiceField(choices=offerchoices) self.fields['offer_amount'] = forms.IntegerField(min_value=1, widget=forms.NumberInput( attrs={'size':'10'}))
def __init__(self, trade, *args, **kwargs): super(Accepttradeform, self).__init__(*args, **kwargs) self.fields['amount'] = forms.IntegerField(min_value=1, max_value=trade.amount, widget=forms.NumberInput( attrs={'size':'2'}))
def __init__(self, world, logtype, *args, **kwargs): super(DeleteByTargetForm, self).__init__(*args, **kwargs) if logtype == 'war': listlogs = Warlog.objects.filter(owner=world) listtargets = [] for log in listlogs: if log.target not in listtargets: listtargets.append(log.target) elif logtype == 'res': listlogs = ResourceLog.objects.filter(owner=world) listtargets = [] for log in listlogs: if log.target not in listtargets: listtargets.append(log.target) elif logtype == 'reccomm': listlogs = Comm.objects.filter(target=world) listtargets = [] for log in listlogs: if log.sender not in listtargets: listtargets.append(log.sender) elif logtype == 'sentcomm': listlogs = SentComm.objects.filter(sender=world) listtargets = [] for log in listlogs: if log.target not in listtargets: listtargets.append(log.target) TARGET_CHOICES = [(target.pk, target.name) for target in listtargets] self.fields["target"] = forms.IntegerField(widget=forms.Select(choices=TARGET_CHOICES), label="Select World")
def __init__(self, fleet1, fleet2, *args, **kwargs): super(Shipexchangeform, self).__init__(*args, **kwargs) self.highest = None self.fleet1 = fleet1.pk self.fleet2 = fleet2.pk for ship in v.shipindices: if fleet1.__dict__[ship] > 0 or fleet2.__dict__[ship] > 0: self.highest = ship for ship in v.shipindices[:v.shipindices.index(self.highest)+1]: #only ships in fleet maxships = fleet1.__dict__[ship] + fleet2.__dict__[ship] self.fields['%s %s' % (fleet1.pk, ship)] = forms.IntegerField(min_value=0, max_value=maxships, widget=forms.NumberInput(attrs={'size':'4'})) self.fields['%s %s' % (fleet2.pk, ship)] = forms.IntegerField(min_value=0, max_value=maxships, widget=forms.NumberInput(attrs={'size':'4'}))
def __init__(self, world, *args, **kwargs): super(shipbuildform, self).__init__(*args, **kwargs) techlist = ['Freighter'] shiplist = techlist + v.tiers[:v.tiers.index(world.techlevel)+1] #slicing up the tech list allows for a dynamic amount of fields for ship in shiplist: self.fields['%s' % ship.replace(' ', '_').lower() + 's'] = forms.IntegerField(min_value=1, initial=0, required=False) #easier than a long if else if chain
def __init__(self, trade, *args, **kwargs): super(tradeamountform, self).__init__(*args, **kwargs) if trade.offer_type == 'resource': val = trade.owner.__dict__[trade.offer] / trade.offer_amount elif trade.offer_type == 'ship': val = trade.fleet_source.__dict__[trade.offer] elif trade.offer_type == 'blueprint': bp = Blueprint_license.objects.get(pk=trade.blueprint_pk) val = trade.owner.blueprints.all().filter(model=bp.model, amount=bp.amount) maxval = val / trade.offer_amount self.fields['tradeno'] = forms.IntegerField(min_value=1, max_value=maxval)
def __init__(self, *args, **kwargs): super(BalancerCustomForm, self).__init__(*args, **kwargs) for i in xrange(1, 11): self.fields['player_%s' % i] = forms.CharField(label='Player %s' % i) self.fields['MMR_%s' % i] = forms.IntegerField(label='MMR %s' % i, min_value=0, initial=0)
def add_fields(self, form, index): super(EventOccurrenceCustomFormSet,self).add_fields(form,index) form.fields['startTime'] = forms.SplitDateTimeField(label=_("Start Time"),input_time_formats=['%I:%M%p','%-I:%M%p'], widget=widgets.SplitDateTimeWidget) form.fields['endTime'] = forms.SplitDateTimeField(label=_("End Time"),input_time_formats=['%I:%M%p','%-I:%M%p'], widget=widgets.SplitDateTimeWidget) form.fields['extraOccurrencesToAdd'] = forms.IntegerField(label=_("Repeat __ times:"),initial=0,min_value=0,max_value=100,required=False) form.fields['extraOccurrenceRule'] = forms.ChoiceField(label=_("Every:"),choices=EVENT_REPEAT_CHOICES,required=False) form.fields['sendReminderTo'] = forms.ChoiceField(label=_("Send A Reminder To:"),choices=REMINDER_SET_CHOICES,initial='none',required=False) form.fields['sendReminderWhen'] = forms.ChoiceField(label=_("Before:"),choices=REMINDER_TIME_CHOICES,initial=0,required=False) form.fields['sendReminderWhich'] = forms.ChoiceField(label=_("Ahead Of:"),choices=(('all',_('All Occurrences')),('first',_('First Occurrence Only'))),initial='all',required=False) form.fields['sendReminderGroup'] = forms.ModelChoiceField(label=_("Remind Group:"),queryset=Group.objects.all(),required=False) form.fields['sendReminderUsers'] = forms.ModelMultipleChoiceField(label=_("Remind Users:"),queryset=User.objects.filter(staffmember__isnull=False),required=False)
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, max_value=None, min_value=None, *args, **kwargs): self.max_value, self.min_value = max_value, min_value super(IntegerField, self).__init__(*args, **kwargs) if max_value is not None: self.validators.append(validators.MaxValueValidator(max_value)) if min_value is not None: self.validators.append(validators.MinValueValidator(min_value))
def from_native(self, value): if self.allow_empty and value in ('', None): return None try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(IntegerField.default_error_messages['invalid']) return super(IntegerChoiceField, self).from_native(value)
def test_should_integer_convert_int(): assert_conversion(forms.IntegerField, graphene.Int)
def prepare_form(self): class MyForm(forms.Form): name = forms.CharField(label='??') parent = forms.IntegerField(label='???', required=False, widget=widgets.ForeignKeyPopupWidget(self, models.MediaFile, 'id')) number = forms.CharField(label='???', required=False, help='????????????') media_file = forms.FileField(label='??????', required=False)
def test_subfields(self): """Test accessing bound subfields""" form = self.SimpleForm(data=self.simple_valid_data) a_bound_field = form['simple_field']['a'] self.assertIsInstance(a_bound_field.field, forms.IntegerField) self.assertEqual(a_bound_field.html_name, 'simple_field-a')
def rel_db_type(self, connection): return IntegerField().db_type(connection=connection)