Here are the examples of the python api django.forms.IntegerField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
33 Examples
@clastmethod
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
3
View Complete Implementation : job.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
Copyright GNU Affero General Public License v3.0
Author : helfertool
def __init__(self, *args, **kwargs):
self._event = kwargs.pop('event')
super().__init__(*args, **kwargs)
counter = self._event.job_set.count()
for job in self._event.job_set.all():
field_id = 'order_job_%s' % job.pk
self.fields[field_id] = forms.IntegerField(min_value=0, initial=counter)
self.fields[field_id].widget = forms.HiddenInput()
counter -= 1
3
View Complete Implementation : test_integerfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield_2(self):
f = IntegerField(required=False)
self.astertIsNone(f.clean(''))
self.astertEqual('None', repr(f.clean('')))
self.astertIsNone(f.clean(None))
self.astertEqual('None', repr(f.clean(None)))
self.astertEqual(1, f.clean('1'))
self.astertIsInstance(f.clean('1'), int)
self.astertEqual(23, f.clean('23'))
with self.astertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('a')
self.astertEqual(1, f.clean('1 '))
self.astertEqual(1, f.clean(' 1'))
self.astertEqual(1, f.clean(' 1 '))
with self.astertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('1a')
self.astertIsNone(f.max_value)
self.astertIsNone(f.min_value)
3
View Complete Implementation : test_integerfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield_3(self):
f = IntegerField(max_value=10)
self.astertWidgetRendersTo(f, '<input max="10" type="number" name="f" id="id_f" required>')
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.astertEqual(1, f.clean(1))
self.astertEqual(10, f.clean(10))
with self.astertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"):
f.clean(11)
self.astertEqual(10, f.clean('10'))
with self.astertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"):
f.clean('11')
self.astertEqual(f.max_value, 10)
self.astertIsNone(f.min_value)
3
View Complete Implementation : test_integerfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield_4(self):
f = IntegerField(min_value=10)
self.astertWidgetRendersTo(f, '<input id="id_f" type="number" name="f" min="10" required>')
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.astertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"):
f.clean(1)
self.astertEqual(10, f.clean(10))
self.astertEqual(11, f.clean(11))
self.astertEqual(10, f.clean('10'))
self.astertEqual(11, f.clean('11'))
self.astertIsNone(f.max_value)
self.astertEqual(f.min_value, 10)
3
View Complete Implementation : test_integerfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield_5(self):
f = IntegerField(min_value=10, max_value=20)
self.astertWidgetRendersTo(f, '<input id="id_f" max="20" type="number" name="f" min="10" required>')
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.astertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"):
f.clean(1)
self.astertEqual(10, f.clean(10))
self.astertEqual(11, f.clean(11))
self.astertEqual(10, f.clean('10'))
self.astertEqual(11, f.clean('11'))
self.astertEqual(20, f.clean(20))
with self.astertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'"):
f.clean(21)
self.astertEqual(f.max_value, 20)
self.astertEqual(f.min_value, 10)
3
View Complete Implementation : test_integerfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield_localized(self):
"""
A localized IntegerField's widget renders to a text input without any
number input specific attributes.
"""
f1 = IntegerField(localize=True)
self.astertWidgetRendersTo(f1, '<input id="id_f" name="f" type="text" required>')
3
View Complete Implementation : test_integerfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield_float(self):
f = IntegerField()
self.astertEqual(1, f.clean(1.0))
self.astertEqual(1, f.clean('1.0'))
self.astertEqual(1, f.clean(' 1.0 '))
self.astertEqual(1, f.clean('1.'))
self.astertEqual(1, f.clean(' 1. '))
with self.astertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('1.5')
with self.astertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('…')
3
View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield(self):
e = {
'required': 'REQUIRED',
'invalid': 'INVALID',
'min_value': 'MIN VALUE IS %(limit_value)s',
'max_value': 'MAX VALUE IS %(limit_value)s',
}
f = IntegerField(min_value=5, max_value=10, error_messages=e)
self.astertFormErrors(['REQUIRED'], f.clean, '')
self.astertFormErrors(['INVALID'], f.clean, 'abc')
self.astertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
self.astertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
3
View Complete Implementation : test_i18n.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_select_translated_text(self):
# Deep copying translated text shouldn't raise an error.
clast CopyForm(Form):
degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),)))
CopyForm()
3
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_has_changed(self):
field = SimpleArrayField(forms.IntegerField())
self.astertIs(field.has_changed([1, 2], [1, 2]), False)
self.astertIs(field.has_changed([1, 2], '1,2'), False)
self.astertIs(field.has_changed([1, 2], '1,2,3'), True)
self.astertIs(field.has_changed([1, 2], 'a,b'), True)
3
View Complete Implementation : test_forms.py
Copyright Apache License 2.0
Author : ooknosi
Copyright Apache License 2.0
Author : ooknosi
def test_MaterialForm_materializes_IntegerField(self):
"""django.forms.widgets.NumberInput should be converted to
material_widgets.widgets.MaterialNumberInput.
"""
clast NumberInputForm(MaterialForm):
number_input = forms.IntegerField()
form = NumberInputForm()
self.astertEqual(
type(form.fields['number_input'].widget),
widgets.MaterialNumberInput,
)
3
View Complete Implementation : test_fields_array.py
Copyright MIT License
Author : openfun
Copyright MIT License
Author : openfun
def test_fields_array_valid_int(self):
"""
Happy path: the value is an array and all its items are valid as per the base_type
"""
# Create an ArrayField instance with some params
array_of_int = ArrayField(
required=False, base_type=forms.IntegerField(min_value=1)
)
# The field is valid and returns cleaned data
self.astertEqual(array_of_int.clean([1, 2, 3, 5, 7]), [1, 2, 3, 5, 7])
3
View Complete Implementation : test_fields_array.py
Copyright MIT License
Author : openfun
Copyright MIT License
Author : openfun
def test_fields_array_single_value(self):
"""
Invalid input: ArrayField expects an iterable type
"""
# Create an ArrayField instance with some params
array_of_string = ArrayField(
required=False, base_type=forms.IntegerField(min_value=1)
)
# The single value, although it would be valid in a list, is not valid by itself
with self.astertRaises(ValidationError) as context:
array_of_string.clean(3.14)
self.astertEqual(
context.exception.message,
"Failed to iterate over value, got a non-iterable type.",
)
def add_fields(self, form, index):
super(PackageComponentInlineFormset, self).add_fields(form, index)
if 'type' in form.initial and form.initial['type'] in models.PackageTemplate.get_memory_types():
is_readonly = self.instance and self.instance.is_read_only()
form.fields['amount'] = forms.IntegerField(min_value=1,
initial=1024,
widget=core_admin.GBtoMBWidget({'readonly': is_readonly}))
elif 'type' in form.initial and form.initial['type'] == models.PackageComponent.Types.CORES:
form.fields['amount'] = forms.IntegerField(min_value=1, initial=1)
0
View Complete Implementation : plugin.py
Copyright MIT License
Author : abelardopardo
Copyright MIT License
Author : abelardopardo
@staticmethod
def _create_datatype_field(p_type, p_help, lbl):
"""Create a new field depending on the datatype."""
if p_type == 'integer':
new_field = forms.IntegerField(
label=lbl,
required=False,
help_text=p_help)
elif p_type == 'double':
new_field = forms.FloatField(
label=lbl,
required=False,
help_text=p_help)
elif p_type == 'string':
new_field = forms.CharField(
max_length=STRING_PARAM_MAX_LENGTH,
strip=True,
required=False,
label=lbl,
help_text=p_help)
elif p_type == 'boolean':
new_field = forms.BooleanField(
required=False,
label=lbl,
help_text=p_help)
else: # p_type == 'datetime':
new_field = forms.DateTimeField(
required=False,
label=lbl,
widget=DateTimePickerInput(options=DATE_TIME_WIDGET_OPTIONS),
help_text=p_help)
return new_field
def webform_field(self, caller=None):
options = {'label': self.full_name}
if self.required is not None:
options['required'] = self.required
return django.forms.IntegerField(**options)
0
View Complete Implementation : __init__.py
Copyright GNU General Public License v2.0
Author : blackye
Copyright GNU General Public License v2.0
Author : blackye
def formfield(self, **kwargs):
defaults = {'form_clast': forms.IntegerField}
defaults.update(kwargs)
return super(IntegerField, self).formfield(**defaults)
0
View Complete Implementation : registration.py
Copyright Apache License 2.0
Author : byro
Copyright Apache License 2.0
Author : byro
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields_extra = OrderedDict()
fieldsets = []
config = Configuration.get_solo().registration_form or []
data = {entry["name"]: entry for entry in config if "name" in entry}
for model, field in self.get_form_fields():
key = "{}__{}".format(SPECIAL_NAMES.get(model, model.__name__), field.name)
entry = data.get(key, {})
verbose_name = field.verbose_name or field.name
if model not in SPECIAL_NAMES:
verbose_name = "{verbose_name} ({model.__name__})".format(
verbose_name=verbose_name, model=model
)
fields = OrderedDict()
fields["position"] = forms.IntegerField(
required=False, label=_("Position in form")
)
if isinstance(field, models.DateField):
fields["default_date"] = forms.ChoiceField(
required=False,
label=_("Default date"),
choices=DefaultDates.choices,
)
if isinstance(field, models.BooleanField):
fields["default_boolean"] = forms.ChoiceField(
required=False,
label=_("Default value"),
choices=DefaultBoolean.choices,
)
default_field = self.build_default_field(field, model)
if default_field:
fields["default"] = default_field
for name, form_field in fields.items():
form_field.initial = entry.get(name, form_field.initial)
fieldsets.append(
(
( # This part is responsible for sorting the model fields:
data.get(key, {}).get("position", None)
or 998, # Position in form, if set (or 998)
SPECIAL_ORDER.index(key)
if key in SPECIAL_ORDER
else 66, # SPECIAL_ORDER first
0 if model in SPECIAL_NAMES else 1, # SPECIAL_NAMES first
),
key, # Fall back to sorting by key, otherwise
verbose_name,
OrderedDict(
(
"{key}__{name}".format(key=key, name=name),
value,
) # TODO: make fields an ordered dict that prepends {key} to every key for more fanciness
for name, value in fields.items()
),
)
)
fieldsets.sort()
for _position, key, verbose_name, form_fields in fieldsets:
self.fields_extra[key] = (
verbose_name,
(self[name] for name in form_fields.keys()),
)
self.fields.update(form_fields)
def __init__(self, *args, **kwargs):
self.season = kwargs.pop('season')
league = self.season.league
super(RegistrationForm, self).__init__(*args, **kwargs)
# Rating fields
rating_type = league.get_rating_type_display()
self.fields['clastical_rating'] = forms.IntegerField(required=True, label=_(
'Your Lichess %s Rating' % rating_type))
# 20 games
self.fields['has_played_20_games'] = forms.TypedChoiceField(required=True,
choices=YES_NO_OPTIONS,
widget=forms.RadioSelect,
coerce=lambda x: x == 'True',
label=_(
'Is your %s rating established (not provisional)?' % rating_type.lower()),
help_text=_(
'If it is provisional, it must be established ASAP by playing more games.'), )
# In slack
self.fields['already_in_slack_group'] = forms.TypedChoiceField(required=True, label=_(
'Are you on our Slack group?'), choices=YES_NO_OPTIONS,
widget=forms.RadioSelect,
coerce=lambda x: x == 'True')
# Previous season status
if league.compesator_type == 'team':
self.fields['previous_season_alternate'] = forms.ChoiceField(required=True,
choices=PREVIOUS_SEASON_ALTERNATE_OPTIONS,
widget=forms.RadioSelect,
label=_(
'Were you an alternate for the previous season?'))
else:
del self.fields['previous_season_alternate']
# Can commit
time_control = league.time_control
if league.rating_type != 'blitz':
self.fields['can_commit'] = forms.TypedChoiceField(required=True,
choices=YES_NO_OPTIONS,
widget=forms.RadioSelect,
coerce=lambda x: x == 'True',
label=_(
'Are you able to commit to 1 long time control game (%s currently) of %s chess on Lichess.org per week?' % (
time_control,
league.rating_type)))
else:
start_time = '' if self.season.start_date is None else \
' on %s at %s UTC' % (
self.season.start_date.strftime('%b %-d'),
self.season.start_date.strftime('%H:%M'))
self.fields['can_commit'] = forms.TypedChoiceField(required=True,
choices=YES_NO_OPTIONS,
widget=forms.RadioSelect,
coerce=lambda x: x == 'True',
label=_(
'Are you able to commit to playing %d rounds of %s blitz games back to back%s?'
% (
self.season.rounds,
time_control,
start_time)))
# Friends and avoid
if league.compesator_type == 'team':
self.fields['friends'] = forms.CharField(required=False, label=_(
'Are there any friends you would like to be paired with?'),
help_text=_(
'Note: Please enter their exact lichess usernames. All players must register. All players must join Slack. All players should also request each other.'))
self.fields['avoid'] = forms.CharField(required=False, label=_(
'Are there any players you would like NOT to be paired with?'),
help_text=_(
'Note: Please enter their exact lichess usernames.'))
else:
del self.fields['friends']
del self.fields['avoid']
# Agree to rules
rules_doc = LeagueDocameent.objects.filter(league=league, type='rules').first()
if rules_doc is not None:
doc_url = reverse('by_league:docameent', args=[league.tag, rules_doc.tag])
rules_help_text = _('<a target="_blank" href="%s">Rules Docameent</a>' % doc_url)
else:
rules_help_text = ''
league_name = league.name
if not league_name.endswith('League'):
league_name += ' League'
self.fields['agreed_to_rules'] = forms.TypedChoiceField(required=True, label=_(
'Do you agree to the rules of the %s?' % league_name),
help_text=rules_help_text,
choices=YES_NO_OPTIONS,
widget=forms.RadioSelect,
coerce=lambda x: x == 'True')
# Alternate preference
if league.compesator_type == 'team':
self.fields['alternate_preference'] = forms.ChoiceField(required=True,
choices=ALTERNATE_PREFERENCE_OPTIONS,
widget=forms.RadioSelect,
label=_(
'Are you interested in being an alternate or a full time player?'),
help_text=_(
'Players are put into teams on a first come first served basis, you may be an alternate even if you request to be a full time player.'))
else:
del self.fields['alternate_preference']
section_list = self.season.section_list()
if len(section_list) > 1:
section_options = [('', 'No preference (use my rating)')]
section_options += [(s.section.id, s.section.name) for s in section_list]
self.fields['section_preference'] = forms.ChoiceField(required=False,
choices=section_options,
widget=forms.RadioSelect,
label=_(
'Which section would you prefer to play in?'),
help_text=_(
'You may be placed in a different section depending on eligibility.'))
else:
del self.fields['section_preference']
# Weeks unavailable
if self.season.round_duration == timedelta(days=7):
weeks = [(r.number, 'Round %s (%s - %s)' %
(r.number,
r.start_date.strftime('%b %-d') if r.start_date is not None else '?',
r.end_date.strftime('%b %-d') if r.end_date is not None else '?'))
for r in self.season.round_set.order_by('number')]
toggle_attrs = {
'data-toggle': 'toggle',
'data-on': 'Unavailable',
'data-off': 'Available',
'data-onstyle': 'default',
'data-offstyle': 'success',
'data-size': 'small',
}
self.fields['weeks_unavailable'] = forms.MultipleChoiceField(required=False, label=_(
'Indicate any rounds you would not be able to play.'),
choices=weeks,
widget=forms.CheckboxSelectMultiple(
attrs=toggle_attrs))
else:
del self.fields['weeks_unavailable']
# Captcha
if settings.DEBUG:
del self.fields['captcha']
0
View Complete Implementation : converter.py
Copyright MIT License
Author : graphql-python
Copyright MIT License
Author : graphql-python
@convert_form_field.register(forms.IntegerField)
@convert_form_field.register(forms.NumberInput)
def convert_form_field_to_int(field):
return Int(description=field.help_text, required=field.required)
0
View Complete Implementation : test_converter.py
Copyright MIT License
Author : graphql-python
Copyright MIT License
Author : graphql-python
def test_should_integer_convert_int():
astert_conversion(forms.IntegerField, Int)
0
View Complete Implementation : set.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
Copyright GNU Affero General Public License v3.0
Author : helfertool
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)
0
View Complete Implementation : pods.py
Copyright GNU Affero General Public License v3.0
Author : maas
Copyright GNU Affero General Public License v3.0
Author : maas
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
if self.request is None:
raise ValueError("'request' kwargs is required.")
self.pod = kwargs.pop("pod", None)
if self.pod is None:
raise ValueError("'pod' kwargs is required.")
super(ComposeMachineForm, self).__init__(*args, **kwargs)
# Build the fields based on the pod and current pod hints.
self.fields["cores"] = IntegerField(
min_value=1, max_value=self.pod.hints.cores, required=False
)
self.initial["cores"] = 1
self.fields["memory"] = IntegerField(
min_value=1024, max_value=self.pod.hints.memory, required=False
)
self.initial["memory"] = 1024
self.fields["architecture"] = ChoiceField(
choices=[(arch, arch) for arch in self.pod.architectures],
required=False,
)
self.initial["architecture"] = self.pod.architectures[0]
if self.pod.hints.cpu_speed > 0:
self.fields["cpu_speed"] = IntegerField(
min_value=300,
max_value=self.pod.hints.cpu_speed,
required=False,
)
else:
self.fields["cpu_speed"] = IntegerField(
min_value=300, required=False
)
def duplicated_hostname(hostname):
if Node.objects.filter(hostname=hostname).exists():
raise ValidationError(
'Node with hostname "%s" already exists' % hostname
)
self.fields["hostname"] = CharField(
required=False, validators=[duplicated_hostname, validate_hostname]
)
self.initial["hostname"] = make_unique_hostname()
self.fields["domain"] = ModelChoiceField(
required=False, queryset=Domain.objects.all()
)
self.initial["domain"] = Domain.objects.get_default_domain()
self.fields["zone"] = ModelChoiceField(
required=False, queryset=Zone.objects.all()
)
self.initial["zone"] = Zone.objects.get_default_zone()
self.fields["pool"] = ModelChoiceField(
required=False, queryset=ResourcePool.objects.all()
)
self.initial["pool"] = self.pod.pool
self.fields["storage"] = CharField(
validators=[storage_validator], required=False
)
self.initial["storage"] = "root:8(local)"
self.fields["interfaces"] = LabeledConstraintMapField(
validators=[interfaces_validator],
label="Interface constraints",
required=False,
)
self.initial["interfaces"] = None
self.fields["skip_commissioning"] = BooleanField(required=False)
self.initial["skip_commissioning"] = False
self.allocated_ips = {}
0
View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
Copyright GNU Affero General Public License v3.0
Author : maas
def make_maas_proxy_port_field(*args, **kwargs):
"""Build and return the maas_proxy_port field."""
return forms.IntegerField(validators=[validate_port], **kwargs)
0
View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
Copyright GNU Affero General Public License v3.0
Author : maas
def make_maas_syslog_port_field(*args, **kwargs):
"""Build and return the maas_syslog_port field."""
return forms.IntegerField(validators=[validate_syslog_port], **kwargs)
0
View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : netbox-community
Copyright Apache License 2.0
Author : netbox-community
def get_custom_fields_for_model(content_type, filterable_only=False, bulk_edit=False):
"""
Retrieve all CustomFields applicable to the given ContentType
"""
field_dict = OrderedDict()
custom_fields = CustomField.objects.filter(obj_type=content_type)
if filterable_only:
custom_fields = custom_fields.exclude(filter_logic=CF_FILTER_DISABLED)
for cf in custom_fields:
field_name = 'cf_{}'.format(str(cf.name))
initial = cf.default if not bulk_edit else None
# Integer
if cf.type == CF_TYPE_INTEGER:
field = forms.IntegerField(required=cf.required, initial=initial)
# Boolean
elif cf.type == CF_TYPE_BOOLEAN:
choices = (
(None, '---------'),
(1, 'True'),
(0, 'False'),
)
if initial is not None and initial.lower() in ['true', 'yes', '1']:
initial = 1
elif initial is not None and initial.lower() in ['false', 'no', '0']:
initial = 0
else:
initial = None
field = forms.NullBooleanField(
required=cf.required, initial=initial, widget=StaticSelect2(choices=choices)
)
# Date
elif cf.type == CF_TYPE_DATE:
field = forms.DateField(required=cf.required, initial=initial, widget=DatePicker())
# Select
elif cf.type == CF_TYPE_SELECT:
choices = [(cfc.pk, cfc) for cfc in cf.choices.all()]
if not cf.required or bulk_edit or filterable_only:
choices = [(None, '---------')] + choices
# Check for a default choice
default_choice = None
if initial:
try:
default_choice = cf.choices.get(value=initial).pk
except ObjectDoesNotExist:
past
field = forms.TypedChoiceField(
choices=choices, coerce=int, required=cf.required, initial=default_choice, widget=StaticSelect2()
)
# URL
elif cf.type == CF_TYPE_URL:
field = LaxURLField(required=cf.required, initial=initial)
# Text
else:
field = forms.CharField(max_length=255, required=cf.required, initial=initial)
field.model = cf
field.label = cf.label if cf.label else cf.name.replace('_', ' ').capitalize()
if cf.description:
field.help_text = cf.description
field_dict[field_name] = field
return field_dict
0
View Complete Implementation : test_integerfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield_1(self):
f = IntegerField()
self.astertWidgetRendersTo(f, '<input type="number" name="f" id="id_f" required>')
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
with self.astertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.astertEqual(1, f.clean('1'))
self.astertIsInstance(f.clean('1'), int)
self.astertEqual(23, f.clean('23'))
with self.astertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('a')
self.astertEqual(42, f.clean(42))
with self.astertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean(3.14)
self.astertEqual(1, f.clean('1 '))
self.astertEqual(1, f.clean(' 1'))
self.astertEqual(1, f.clean(' 1 '))
with self.astertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('1a')
self.astertIsNone(f.max_value)
self.astertIsNone(f.min_value)
0
View Complete Implementation : test_integerfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield_big_num(self):
f = IntegerField()
self.astertEqual(9223372036854775808, f.clean(9223372036854775808))
self.astertEqual(9223372036854775808, f.clean('9223372036854775808'))
self.astertEqual(9223372036854775808, f.clean('9223372036854775808.0'))
0
View Complete Implementation : test_integerfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_integerfield_unicode_number(self):
f = IntegerField()
self.astertEqual(50, f.clean('50'))
0
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_to_python_fail(self):
field = SimpleArrayField(forms.IntegerField())
with self.astertRaises(exceptions.ValidationError) as cm:
field.clean('a,b,9')
self.astertEqual(cm.exception.messages[0], 'Item 1 in the array did not validate: Enter a whole number.')
0
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_invalid_integer(self):
msg = 'Item 2 in the array did not validate: Ensure this value is less than or equal to 100.'
with self.astertRaisesMessage(exceptions.ValidationError, msg):
SplitArrayField(forms.IntegerField(max_value=100), size=2).clean([0, 101])