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.
44 Examples
3
Source : forms.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['page_length'] = IntegerField(max_value=100, min_value=10)
class EventForm(ModelForm):
3
Source : __init__.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def formfield(self, **kwargs):
defaults = {'form_class': forms.IntegerField}
defaults.update(kwargs)
return super().formfield(**defaults)
class BigIntegerField(IntegerField):
3
Source : __init__.py
with MIT License
from Air-999
with MIT License
from Air-999
def formfield(self, **kwargs):
return super().formfield(**{
'form_class': forms.IntegerField,
**kwargs,
})
class BigIntegerField(IntegerField):
3
Source : __init__.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def formfield(self, **kwargs):
defaults = {'form_class': forms.IntegerField}
defaults.update(kwargs)
return super(IntegerField, self).formfield(**defaults)
class BigIntegerField(IntegerField):
3
Source : forms.py
with GNU General Public License v3.0
from foonsun
with GNU General Public License v3.0
from foonsun
def _attr_integer_field(attribute):
return forms.IntegerField(label=attribute.name,
required=attribute.required)
def _attr_boolean_field(attribute):
3
Source : test_integerfield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_integerfield_3(self):
f = IntegerField(max_value=10)
self.assertWidgetRendersTo(f, ' < input max="10" type="number" name="f" id="id_f" required />')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.assertEqual(1, f.clean(1))
self.assertEqual(10, f.clean(10))
with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"):
f.clean(11)
self.assertEqual(10, f.clean('10'))
with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"):
f.clean('11')
self.assertEqual(f.max_value, 10)
self.assertIsNone(f.min_value)
def test_integerfield_4(self):
3
Source : test_integerfield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_integerfield_4(self):
f = IntegerField(min_value=10)
self.assertWidgetRendersTo(f, ' < input id="id_f" type="number" name="f" min="10" required />')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"):
f.clean(1)
self.assertEqual(10, f.clean(10))
self.assertEqual(11, f.clean(11))
self.assertEqual(10, f.clean('10'))
self.assertEqual(11, f.clean('11'))
self.assertIsNone(f.max_value)
self.assertEqual(f.min_value, 10)
def test_integerfield_5(self):
3
Source : test_integerfield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_integerfield_5(self):
f = IntegerField(min_value=10, max_value=20)
self.assertWidgetRendersTo(f, ' < input id="id_f" max="20" type="number" name="f" min="10" required />')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"):
f.clean(1)
self.assertEqual(10, f.clean(10))
self.assertEqual(11, f.clean(11))
self.assertEqual(10, f.clean('10'))
self.assertEqual(11, f.clean('11'))
self.assertEqual(20, f.clean(20))
with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'"):
f.clean(21)
self.assertEqual(f.max_value, 20)
self.assertEqual(f.min_value, 10)
def test_integerfield_localized(self):
3
Source : test_integerfield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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.assertWidgetRendersTo(f1, ' < input id="id_f" name="f" type="text" required />')
def test_integerfield_float(self):
3
Source : test_integerfield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_integerfield_float(self):
f = IntegerField()
self.assertEqual(1, f.clean(1.0))
self.assertEqual(1, f.clean('1.0'))
self.assertEqual(1, f.clean(' 1.0 '))
self.assertEqual(1, f.clean('1.'))
self.assertEqual(1, f.clean(' 1. '))
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('1.5')
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('…')
def test_integerfield_big_num(self):
3
Source : test_integerfield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_integerfield_big_num(self):
f = IntegerField()
self.assertEqual(9223372036854775808, f.clean(9223372036854775808))
self.assertEqual(9223372036854775808, f.clean('9223372036854775808'))
self.assertEqual(9223372036854775808, f.clean('9223372036854775808.0'))
def test_integerfield_unicode_number(self):
3
Source : test_error_messages.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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.assertFormErrors(['REQUIRED'], f.clean, '')
self.assertFormErrors(['INVALID'], f.clean, 'abc')
self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
def test_floatfield(self):
3
Source : test_forms.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_get_initial_for_field(self):
class PersonForm(Form):
first_name = CharField(initial='John')
last_name = CharField(initial='Doe')
age = IntegerField()
occupation = CharField(initial=lambda: 'Unknown')
form = PersonForm(initial={'first_name': 'Jane'})
self.assertEqual(form.get_initial_for_field(form.fields['age'], 'age'), None)
self.assertEqual(form.get_initial_for_field(form.fields['last_name'], 'last_name'), 'Doe')
# Form.initial overrides Field.initial.
self.assertEqual(form.get_initial_for_field(form.fields['first_name'], 'first_name'), 'Jane')
# Callables are evaluated.
self.assertEqual(form.get_initial_for_field(form.fields['occupation'], 'occupation'), 'Unknown')
def test_changed_data(self):
3
Source : test_forms.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_label_has_required_css_class(self):
"""
#17922 - required_css_class is added to the label_tag() of required fields.
"""
class SomeForm(Form):
required_css_class = 'required'
field = CharField(max_length=10)
field2 = IntegerField(required=False)
f = SomeForm({'field': 'test'})
self.assertHTMLEqual(f['field'].label_tag(), ' < label for="id_field" class="required">Field: < /label>')
self.assertHTMLEqual(
f['field'].label_tag(attrs={'class': 'foo'}),
' < label for="id_field" class="foo required">Field: < /label>'
)
self.assertHTMLEqual(f['field2'].label_tag(), ' < label for="id_field2">Field2: < /label>')
def test_label_split_datetime_not_displayed(self):
3
Source : test_forms.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_multivalue_initial_data(self):
"""
#23674 -- invalid initial data should not break form.changed_data()
"""
class DateAgeField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (DateField(label="Date"), IntegerField(label="Age"))
super(DateAgeField, self).__init__(fields=fields, *args, **kwargs)
class DateAgeForm(Form):
date_age = DateAgeField()
data = {"date_age": ["1998-12-06", 16]}
form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]})
self.assertTrue(form.has_changed())
def test_multivalue_optional_subfields(self):
3
Source : test_formsets.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_validate_max_ignores_forms_marked_for_deletion(self):
class CheckForm(Form):
field = IntegerField()
data = {
'check-TOTAL_FORMS': '2',
'check-INITIAL_FORMS': '0',
'check-MAX_NUM_FORMS': '1',
'check-0-field': '200',
'check-0-DELETE': '',
'check-1-field': '50',
'check-1-DELETE': 'on',
}
CheckFormSet = formset_factory(CheckForm, max_num=1, validate_max=True,
can_delete=True)
formset = CheckFormSet(data, prefix='check')
self.assertTrue(formset.is_valid())
def test_formset_total_error_count(self):
3
Source : test_i18n.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_select_translated_text(self):
# Deep copying translated text shouldn't raise an error.
class CopyForm(Form):
degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),)))
CopyForm()
3
Source : test_array.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_to_python_fail(self):
field = SimpleArrayField(forms.IntegerField())
with self.assertRaises(exceptions.ValidationError) as cm:
field.clean('a,b,9')
self.assertEqual(cm.exception.messages[0], 'Item 0 in the array did not validate: Enter a whole number.')
def test_validate_fail(self):
3
Source : test_array.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_invalid_integer(self):
msg = 'Item 1 in the array did not validate: Ensure this value is less than or equal to 100.'
with self.assertRaisesMessage(exceptions.ValidationError, msg):
SplitArrayField(forms.IntegerField(max_value=100), size=2).clean([0, 101])
# To locate the widget's template.
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.postgres'})
3
Source : test_forms.py
with MIT License
from gradam
with MIT License
from gradam
def test_default_different_values(self, model_class, init_value, expected_value):
default = [1]
data = {}
if init_value is not None:
data["array"] = init_value
field = DynamicArrayField(IntegerField(), required=True, default=default)
form = form_factory(model_class, array=field)(data=data)
assert form.is_valid()
assert form.cleaned_data["array"] == expected_value
3
Source : utils.py
with MIT License
from guidovranken
with MIT License
from guidovranken
def test_forms_IntegerField(inp):
try:
forms.IntegerField().clean(inp)
except:
pass
def test_forms_NullBooleanField(inp):
3
Source : __init__.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def formfield(self, **kwargs):
defaults = {'form_class': forms.IntegerField}
defaults.update(kwargs)
return super(IntegerField, self).formfield(**defaults)
class BigIntegerField(IntegerField):
3
Source : views.py
with GNU General Public License v2.0
from puncoder
with GNU General Public License v2.0
from puncoder
def remove(_request, link_id):
''' Remove a specific link with ID ``link_id`` '''
field = IntegerField(min_value=1)
try:
value = field.clean(link_id)
except ValidationError as err:
json_data = {'rc': 1, 'response': '\n'.join(err.messages)}
return http.JsonResponse(json_data, status=HTTPStatus.BAD_REQUEST)
# this will silently ignore non-existing objects
LinkReference.objects.filter(pk=value).delete()
return http.JsonResponse({
'rc': 0,
'response': 'Link has been removed successfully.'
})
3
Source : utils_test.py
with MIT License
from shinneider
with MIT License
from shinneider
def test_integer_field_parse(self):
field = forms.IntegerField()
self.assertEqual(format_data(field, 1), 1)
self.assertEqual(format_data(field, '1'), 1)
self.assertEqual(format_data(field, '0'), 0)
self.assertRaises(ValidationError, lambda: format_data(field, 1.1))
def test_date_field_parse(self):
3
Source : django-tests-forms_tests-field_tests-test_integerfield.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
def test_integerfield_3(self):
f = IntegerField(max_value=10)
self.assertWidgetRendersTo(f, ' < input max="10" type="number" name="f" id="id_f" required>')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.assertEqual(1, f.clean(1))
self.assertEqual(10, f.clean(10))
with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"):
f.clean(11)
self.assertEqual(10, f.clean('10'))
with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"):
f.clean('11')
self.assertEqual(f.max_value, 10)
self.assertIsNone(f.min_value)
def test_integerfield_4(self):
3
Source : django-tests-forms_tests-field_tests-test_integerfield.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
def test_integerfield_4(self):
f = IntegerField(min_value=10)
self.assertWidgetRendersTo(f, ' < input id="id_f" type="number" name="f" min="10" required>')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"):
f.clean(1)
self.assertEqual(10, f.clean(10))
self.assertEqual(11, f.clean(11))
self.assertEqual(10, f.clean('10'))
self.assertEqual(11, f.clean('11'))
self.assertIsNone(f.max_value)
self.assertEqual(f.min_value, 10)
def test_integerfield_5(self):
3
Source : django-tests-forms_tests-field_tests-test_integerfield.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
def test_integerfield_5(self):
f = IntegerField(min_value=10, max_value=20)
self.assertWidgetRendersTo(f, ' < input id="id_f" max="20" type="number" name="f" min="10" required>')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"):
f.clean(1)
self.assertEqual(10, f.clean(10))
self.assertEqual(11, f.clean(11))
self.assertEqual(10, f.clean('10'))
self.assertEqual(11, f.clean('11'))
self.assertEqual(20, f.clean(20))
with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'"):
f.clean(21)
self.assertEqual(f.max_value, 20)
self.assertEqual(f.min_value, 10)
def test_integerfield_localized(self):
3
Source : django-tests-forms_tests-field_tests-test_integerfield.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
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.assertWidgetRendersTo(f1, ' < input id="id_f" name="f" type="text" required>')
def test_integerfield_float(self):
3
Source : django-tests-forms_tests-tests-test_forms.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
def test_multivalue_initial_data(self):
"""
#23674 -- invalid initial data should not break form.changed_data()
"""
class DateAgeField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (DateField(label="Date"), IntegerField(label="Age"))
super().__init__(fields=fields, *args, **kwargs)
class DateAgeForm(Form):
date_age = DateAgeField()
data = {"date_age": ["1998-12-06", 16]}
form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]})
self.assertTrue(form.has_changed())
def test_multivalue_optional_subfields(self):
0
Source : forms.py
with MIT License
from bihealth
with MIT License
from bihealth
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["regulatory_general_padding"] = forms.IntegerField(
label="padding (bp)", required=False, initial=100,
)
self.fields["regulatory_ensembl"] = forms.MultipleChoiceField(
label="ENSEMBL feature",
required=False,
choices=list(FILTER_FORM_ENSEMBL_CHOICES.items()),
)
self.fields["regulatory_vista"] = forms.MultipleChoiceField(
label="VISTA validation",
required=False,
choices=list(FILTER_FORM_VISTA_CHOICES.items()),
)
self.reg_map_fields = {}
for coll in RegMapCollection.objects.all():
element_field = forms.MultipleChoiceField(
label=coll.title,
required=False,
choices=[("__any__", "any")]
+ [(ret.slug, ret.title) for ret in coll.regelementtype_set.all()],
)
map_field = forms.MultipleChoiceField(
label=coll.title,
required=False,
choices=[("__any__", "any")]
+ [(ret.slug, ret.short_title) for ret in coll.regmap_set.all()],
)
interaction_field = forms.BooleanField(label=coll.title, required=False,)
self.fields["regmap_%s_element" % coll.slug] = element_field
self.fields["regmap_%s_map" % coll.slug] = map_field
self.fields["regmap_%s_interaction" % coll.slug] = interaction_field
self.reg_map_fields["regmap_%s" % coll.slug] = (
coll,
element_field,
map_field,
interaction_field,
)
class FilterForm(
0
Source : test_integerfield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_integerfield_1(self):
f = IntegerField()
self.assertWidgetRendersTo(f, ' < input type="number" name="f" id="id_f" required />')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.assertEqual(1, f.clean('1'))
self.assertIsInstance(f.clean('1'), int)
self.assertEqual(23, f.clean('23'))
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('a')
self.assertEqual(42, f.clean(42))
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean(3.14)
self.assertEqual(1, f.clean('1 '))
self.assertEqual(1, f.clean(' 1'))
self.assertEqual(1, f.clean(' 1 '))
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('1a')
self.assertIsNone(f.max_value)
self.assertIsNone(f.min_value)
def test_integerfield_2(self):
0
Source : test_integerfield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_integerfield_2(self):
f = IntegerField(required=False)
self.assertIsNone(f.clean(''))
self.assertEqual('None', repr(f.clean('')))
self.assertIsNone(f.clean(None))
self.assertEqual('None', repr(f.clean(None)))
self.assertEqual(1, f.clean('1'))
self.assertIsInstance(f.clean('1'), int)
self.assertEqual(23, f.clean('23'))
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('a')
self.assertEqual(1, f.clean('1 '))
self.assertEqual(1, f.clean(' 1'))
self.assertEqual(1, f.clean(' 1 '))
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('1a')
self.assertIsNone(f.max_value)
self.assertIsNone(f.min_value)
def test_integerfield_3(self):
0
Source : test_integerfield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_integerfield_unicode_number(self):
f = IntegerField()
self.assertEqual(50, f.clean('50'))
def test_integerfield_subclass(self):
0
Source : test_forms.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_empty_permitted(self):
# Sometimes (pretty much in formsets) we want to allow a form to pass validation
# if it is completely empty. We can accomplish this by using the empty_permitted
# argument to a form constructor.
class SongForm(Form):
artist = CharField()
name = CharField()
# First let's show what happens id empty_permitted=False (the default):
data = {'artist': '', 'song': ''}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'name': ['This field is required.'], 'artist': ['This field is required.']})
self.assertEqual(form.cleaned_data, {})
# Now let's show what happens when empty_permitted=True and the form is empty.
form = SongForm(data, empty_permitted=True)
self.assertTrue(form.is_valid())
self.assertEqual(form.errors, {})
self.assertEqual(form.cleaned_data, {})
# But if we fill in data for one of the fields, the form is no longer empty and
# the whole thing must pass validation.
data = {'artist': 'The Doors', 'song': ''}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'name': ['This field is required.']})
self.assertEqual(form.cleaned_data, {'artist': 'The Doors'})
# If a field is not given in the data then None is returned for its data. Lets
# make sure that when checking for empty_permitted that None is treated
# accordingly.
data = {'artist': None, 'song': ''}
form = SongForm(data, empty_permitted=True)
self.assertTrue(form.is_valid())
# However, we *really* need to be sure we are checking for None as any data in
# initial that returns False on a boolean call needs to be treated literally.
class PriceForm(Form):
amount = FloatField()
qty = IntegerField()
data = {'amount': '0.0', 'qty': ''}
form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True)
self.assertTrue(form.is_valid())
def test_extracting_hidden_and_visible(self):
0
Source : test_forms.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_error_html_required_html_classes(self):
class Person(Form):
name = CharField()
is_cool = NullBooleanField()
email = EmailField(required=False)
age = IntegerField()
p = Person({})
p.error_css_class = 'error'
p.required_css_class = 'required'
self.assertHTMLEqual(
p.as_ul(),
""" < li class="required error"> < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< label class="required" for="id_name">Name: < /label> < input type="text" name="name" id="id_name" required /> < /li>
< li class="required"> < label class="required" for="id_is_cool">Is cool: < /label>
< select name="is_cool" id="id_is_cool">
< option value="1" selected>Unknown < /option>
< option value="2">Yes < /option>
< option value="3">No < /option>
< /select> < /li>
< li> < label for="id_email">Email: < /label> < input type="email" name="email" id="id_email" /> < /li>
< li class="required error"> < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< label class="required" for="id_age">Age: < /label> < input type="number" name="age" id="id_age" required /> < /li>"""
)
self.assertHTMLEqual(
p.as_p(),
""" < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< p class="required error"> < label class="required" for="id_name">Name: < /label>
< input type="text" name="name" id="id_name" required /> < /p>
< p class="required"> < label class="required" for="id_is_cool">Is cool: < /label>
< select name="is_cool" id="id_is_cool">
< option value="1" selected>Unknown < /option>
< option value="2">Yes < /option>
< option value="3">No < /option>
< /select> < /p>
< p> < label for="id_email">Email: < /label> < input type="email" name="email" id="id_email" /> < /p>
< ul class="errorlist"> < li>This field is required. < /li> < /ul>
< p class="required error"> < label class="required" for="id_age">Age: < /label>
< input type="number" name="age" id="id_age" required /> < /p>"""
)
self.assertHTMLEqual(
p.as_table(),
""" < tr class="required error">
< th> < label class="required" for="id_name">Name: < /label> < /th>
< td> < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< input type="text" name="name" id="id_name" required /> < /td> < /tr>
< tr class="required"> < th> < label class="required" for="id_is_cool">Is cool: < /label> < /th>
< td> < select name="is_cool" id="id_is_cool">
< option value="1" selected>Unknown < /option>
< option value="2">Yes < /option>
< option value="3">No < /option>
< /select> < /td> < /tr>
< tr> < th> < label for="id_email">Email: < /label> < /th> < td>
< input type="email" name="email" id="id_email" /> < /td> < /tr>
< tr class="required error"> < th> < label class="required" for="id_age">Age: < /label> < /th>
< td> < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< input type="number" name="age" id="id_age" required /> < /td> < /tr>"""
)
def test_label_has_required_css_class(self):
0
Source : test_forms.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_only_hidden_fields(self):
# A form with *only* hidden fields that has errors is going to be very unusual.
class HiddenForm(Form):
data = IntegerField(widget=HiddenInput)
f = HiddenForm({})
self.assertHTMLEqual(
f.as_p(),
' < ul class="errorlist nonfield">'
' < li>(Hidden field data) This field is required. < /li> < /ul>\n < p> '
' < input type="hidden" name="data" id="id_data" /> < /p>'
)
self.assertHTMLEqual(
f.as_table(),
' < tr> < td colspan="2"> < ul class="errorlist nonfield">'
' < li>(Hidden field data) This field is required. < /li> < /ul>'
' < input type="hidden" name="data" id="id_data" /> < /td> < /tr>'
)
def test_field_named_data(self):
0
Source : test_formsets.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_formset_with_deletion(self):
# FormSets with deletion ######################################################
# We can easily add deletion ability to a FormSet with an argument to
# formset_factory. This will add a boolean field to each form instance. When
# that boolean field is True, the form will be in formset.deleted_forms
ChoiceFormSet = formset_factory(Choice, can_delete=True)
initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}]
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
form_output = []
for form in formset.forms:
form_output.append(form.as_ul())
self.assertHTMLEqual(
'\n'.join(form_output),
""" < li>Choice: < input type="text" name="choices-0-choice" value="Calexico" /> < /li>
< li>Votes: < input type="number" name="choices-0-votes" value="100" /> < /li>
< li>Delete: < input type="checkbox" name="choices-0-DELETE" /> < /li>
< li>Choice: < input type="text" name="choices-1-choice" value="Fergie" /> < /li>
< li>Votes: < input type="number" name="choices-1-votes" value="900" /> < /li>
< li>Delete: < input type="checkbox" name="choices-1-DELETE" /> < /li>
< li>Choice: < input type="text" name="choices-2-choice" /> < /li>
< li>Votes: < input type="number" name="choices-2-votes" /> < /li>
< li>Delete: < input type="checkbox" name="choices-2-DELETE" /> < /li>"""
)
# To delete something, we just need to set that form's special delete field to
# 'on'. Let's go ahead and delete Fergie.
data = {
'choices-TOTAL_FORMS': '3', # the number of forms rendered
'choices-INITIAL_FORMS': '2', # the number of forms with initial data
'choices-MIN_NUM_FORMS': '0', # min number of forms
'choices-MAX_NUM_FORMS': '0', # max number of forms
'choices-0-choice': 'Calexico',
'choices-0-votes': '100',
'choices-0-DELETE': '',
'choices-1-choice': 'Fergie',
'choices-1-votes': '900',
'choices-1-DELETE': 'on',
'choices-2-choice': '',
'choices-2-votes': '',
'choices-2-DELETE': '',
}
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertTrue(formset.is_valid())
self.assertEqual(
[form.cleaned_data for form in formset.forms],
[
{'votes': 100, 'DELETE': False, 'choice': 'Calexico'},
{'votes': 900, 'DELETE': True, 'choice': 'Fergie'},
{},
]
)
self.assertEqual(
[form.cleaned_data for form in formset.deleted_forms],
[{'votes': 900, 'DELETE': True, 'choice': 'Fergie'}]
)
# If we fill a form with something and then we check the can_delete checkbox for
# that form, that form's errors should not make the entire formset invalid since
# it's going to be deleted.
class CheckForm(Form):
field = IntegerField(min_value=100)
data = {
'check-TOTAL_FORMS': '3', # the number of forms rendered
'check-INITIAL_FORMS': '2', # the number of forms with initial data
'choices-MIN_NUM_FORMS': '0', # min number of forms
'check-MAX_NUM_FORMS': '0', # max number of forms
'check-0-field': '200',
'check-0-DELETE': '',
'check-1-field': '50',
'check-1-DELETE': 'on',
'check-2-field': '',
'check-2-DELETE': '',
}
CheckFormSet = formset_factory(CheckForm, can_delete=True)
formset = CheckFormSet(data, prefix='check')
self.assertTrue(formset.is_valid())
# If we remove the deletion flag now we will have our validation back.
data['check-1-DELETE'] = ''
formset = CheckFormSet(data, prefix='check')
self.assertFalse(formset.is_valid())
# Should be able to get deleted_forms from a valid formset even if a
# deleted form would have been invalid.
class Person(Form):
name = CharField()
PeopleForm = formset_factory(
form=Person,
can_delete=True)
p = PeopleForm(
{'form-0-name': '', 'form-0-DELETE': 'on', # no name!
'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1,
'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1})
self.assertTrue(p.is_valid())
self.assertEqual(len(p.deleted_forms), 1)
def test_formsets_with_ordering(self):
0
Source : test_formsets.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_formset_with_deletion(self):
# FormSets with deletion ######################################################
# We can easily add deletion ability to a FormSet with an argument to
# formset_factory. This will add a boolean field to each form instance. When
# that boolean field is True, the form will be in formset.deleted_forms
ChoiceFormSet = formset_factory(Choice, can_delete=True)
initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}]
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
form_output = []
for form in formset.forms:
form_output.append(form.as_ul())
self.assertHTMLEqual('\n'.join(form_output), """ < li>Choice: < input type="text" name="choices-0-choice" value="Calexico" /> < /li>
< li>Votes: < input type="number" name="choices-0-votes" value="100" /> < /li>
< li>Delete: < input type="checkbox" name="choices-0-DELETE" /> < /li>
< li>Choice: < input type="text" name="choices-1-choice" value="Fergie" /> < /li>
< li>Votes: < input type="number" name="choices-1-votes" value="900" /> < /li>
< li>Delete: < input type="checkbox" name="choices-1-DELETE" /> < /li>
< li>Choice: < input type="text" name="choices-2-choice" /> < /li>
< li>Votes: < input type="number" name="choices-2-votes" /> < /li>
< li>Delete: < input type="checkbox" name="choices-2-DELETE" /> < /li>""")
# To delete something, we just need to set that form's special delete field to
# 'on'. Let's go ahead and delete Fergie.
data = {
'choices-TOTAL_FORMS': '3', # the number of forms rendered
'choices-INITIAL_FORMS': '2', # the number of forms with initial data
'choices-MAX_NUM_FORMS': '0', # max number of forms
'choices-0-choice': 'Calexico',
'choices-0-votes': '100',
'choices-0-DELETE': '',
'choices-1-choice': 'Fergie',
'choices-1-votes': '900',
'choices-1-DELETE': 'on',
'choices-2-choice': '',
'choices-2-votes': '',
'choices-2-DELETE': '',
}
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertTrue(formset.is_valid())
self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'DELETE': False, 'choice': 'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': 'Fergie'}, {}])
self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': 'Fergie'}])
# If we fill a form with something and then we check the can_delete checkbox for
# that form, that form's errors should not make the entire formset invalid since
# it's going to be deleted.
class CheckForm(Form):
field = IntegerField(min_value=100)
data = {
'check-TOTAL_FORMS': '3', # the number of forms rendered
'check-INITIAL_FORMS': '2', # the number of forms with initial data
'check-MAX_NUM_FORMS': '0', # max number of forms
'check-0-field': '200',
'check-0-DELETE': '',
'check-1-field': '50',
'check-1-DELETE': 'on',
'check-2-field': '',
'check-2-DELETE': '',
}
CheckFormSet = formset_factory(CheckForm, can_delete=True)
formset = CheckFormSet(data, prefix='check')
self.assertTrue(formset.is_valid())
# If we remove the deletion flag now we will have our validation back.
data['check-1-DELETE'] = ''
formset = CheckFormSet(data, prefix='check')
self.assertFalse(formset.is_valid())
# Should be able to get deleted_forms from a valid formset even if a
# deleted form would have been invalid.
class Person(Form):
name = CharField()
PeopleForm = formset_factory(
form=Person,
can_delete=True)
p = PeopleForm(
{'form-0-name': '', 'form-0-DELETE': 'on', # no name!
'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1,
'form-MAX_NUM_FORMS': 1})
self.assertTrue(p.is_valid())
self.assertEqual(len(p.deleted_forms), 1)
def test_formsets_with_ordering(self):
0
Source : test_formsets.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_validate_max_ignores_forms_marked_for_deletion(self):
class CheckForm(Form):
field = IntegerField()
data = {
'check-TOTAL_FORMS': '2',
'check-INITIAL_FORMS': '0',
'check-MAX_NUM_FORMS': '1',
'check-0-field': '200',
'check-0-DELETE': '',
'check-1-field': '50',
'check-1-DELETE': 'on',
}
CheckFormSet = formset_factory(CheckForm, max_num=1, validate_max=True,
can_delete=True)
formset = CheckFormSet(data, prefix='check')
self.assertTrue(formset.is_valid())
def test_formset_total_error_count(self):
0
Source : django-tests-forms_tests-field_tests-test_integerfield.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
def test_integerfield_1(self):
f = IntegerField()
self.assertWidgetRendersTo(f, ' < input type="number" name="f" id="id_f" required>')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.assertEqual(1, f.clean('1'))
self.assertIsInstance(f.clean('1'), int)
self.assertEqual(23, f.clean('23'))
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('a')
self.assertEqual(42, f.clean(42))
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean(3.14)
self.assertEqual(1, f.clean('1 '))
self.assertEqual(1, f.clean(' 1'))
self.assertEqual(1, f.clean(' 1 '))
with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"):
f.clean('1a')
self.assertIsNone(f.max_value)
self.assertIsNone(f.min_value)
def test_integerfield_2(self):
0
Source : django-tests-forms_tests-tests-test_forms.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
def test_get_initial_for_field(self):
now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456)
class PersonForm(Form):
first_name = CharField(initial='John')
last_name = CharField(initial='Doe')
age = IntegerField()
occupation = CharField(initial=lambda: 'Unknown')
dt_fixed = DateTimeField(initial=now)
dt_callable = DateTimeField(initial=lambda: now)
form = PersonForm(initial={'first_name': 'Jane'})
cases = [
('age', None),
('last_name', 'Doe'),
# Form.initial overrides Field.initial.
('first_name', 'Jane'),
# Callables are evaluated.
('occupation', 'Unknown'),
# Microseconds are removed from datetimes.
('dt_fixed', datetime.datetime(2006, 10, 25, 14, 30, 45)),
('dt_callable', datetime.datetime(2006, 10, 25, 14, 30, 45)),
]
for field_name, expected in cases:
with self.subTest(field_name=field_name):
field = form.fields[field_name]
actual = form.get_initial_for_field(field, field_name)
self.assertEqual(actual, expected)
def test_changed_data(self):
0
Source : django-tests-forms_tests-tests-test_forms.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
def test_empty_permitted(self):
# Sometimes (pretty much in formsets) we want to allow a form to pass validation
# if it is completely empty. We can accomplish this by using the empty_permitted
# argument to a form constructor.
class SongForm(Form):
artist = CharField()
name = CharField()
# First let's show what happens id empty_permitted=False (the default):
data = {'artist': '', 'song': ''}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'name': ['This field is required.'], 'artist': ['This field is required.']})
self.assertEqual(form.cleaned_data, {})
# Now let's show what happens when empty_permitted=True and the form is empty.
form = SongForm(data, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
self.assertEqual(form.errors, {})
self.assertEqual(form.cleaned_data, {})
# But if we fill in data for one of the fields, the form is no longer empty and
# the whole thing must pass validation.
data = {'artist': 'The Doors', 'song': ''}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'name': ['This field is required.']})
self.assertEqual(form.cleaned_data, {'artist': 'The Doors'})
# If a field is not given in the data then None is returned for its data. Lets
# make sure that when checking for empty_permitted that None is treated
# accordingly.
data = {'artist': None, 'song': ''}
form = SongForm(data, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
# However, we *really* need to be sure we are checking for None as any data in
# initial that returns False on a boolean call needs to be treated literally.
class PriceForm(Form):
amount = FloatField()
qty = IntegerField()
data = {'amount': '0.0', 'qty': ''}
form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
def test_empty_permitted_and_use_required_attribute(self):
0
Source : django-tests-forms_tests-tests-test_forms.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
def test_error_html_required_html_classes(self):
class Person(Form):
name = CharField()
is_cool = NullBooleanField()
email = EmailField(required=False)
age = IntegerField()
p = Person({})
p.error_css_class = 'error'
p.required_css_class = 'required'
self.assertHTMLEqual(
p.as_ul(),
""" < li class="required error"> < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< label class="required" for="id_name">Name: < /label> < input type="text" name="name" id="id_name" required> < /li>
< li class="required"> < label class="required" for="id_is_cool">Is cool: < /label>
< select name="is_cool" id="id_is_cool">
< option value="unknown" selected>Unknown < /option>
< option value="true">Yes < /option>
< option value="false">No < /option>
< /select> < /li>
< li> < label for="id_email">Email: < /label> < input type="email" name="email" id="id_email"> < /li>
< li class="required error"> < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< label class="required" for="id_age">Age: < /label> < input type="number" name="age" id="id_age" required> < /li>"""
)
self.assertHTMLEqual(
p.as_p(),
""" < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< p class="required error"> < label class="required" for="id_name">Name: < /label>
< input type="text" name="name" id="id_name" required> < /p>
< p class="required"> < label class="required" for="id_is_cool">Is cool: < /label>
< select name="is_cool" id="id_is_cool">
< option value="unknown" selected>Unknown < /option>
< option value="true">Yes < /option>
< option value="false">No < /option>
< /select> < /p>
< p> < label for="id_email">Email: < /label> < input type="email" name="email" id="id_email"> < /p>
< ul class="errorlist"> < li>This field is required. < /li> < /ul>
< p class="required error"> < label class="required" for="id_age">Age: < /label>
< input type="number" name="age" id="id_age" required> < /p>"""
)
self.assertHTMLEqual(
p.as_table(),
""" < tr class="required error">
< th> < label class="required" for="id_name">Name: < /label> < /th>
< td> < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< input type="text" name="name" id="id_name" required> < /td> < /tr>
< tr class="required"> < th> < label class="required" for="id_is_cool">Is cool: < /label> < /th>
< td> < select name="is_cool" id="id_is_cool">
< option value="unknown" selected>Unknown < /option>
< option value="true">Yes < /option>
< option value="false">No < /option>
< /select> < /td> < /tr>
< tr> < th> < label for="id_email">Email: < /label> < /th> < td>
< input type="email" name="email" id="id_email"> < /td> < /tr>
< tr class="required error"> < th> < label class="required" for="id_age">Age: < /label> < /th>
< td> < ul class="errorlist"> < li>This field is required. < /li> < /ul>
< input type="number" name="age" id="id_age" required> < /td> < /tr>"""
)
def test_label_has_required_css_class(self):
0
Source : django-tests-forms_tests-tests-test_forms.py
with Apache License 2.0
from SMAT-Lab
with Apache License 2.0
from SMAT-Lab
def test_only_hidden_fields(self):
# A form with *only* hidden fields that has errors is going to be very unusual.
class HiddenForm(Form):
data = IntegerField(widget=HiddenInput)
f = HiddenForm({})
self.assertHTMLEqual(
f.as_p(),
' < ul class="errorlist nonfield">'
' < li>(Hidden field data) This field is required. < /li> < /ul>\n < p> '
' < input type="hidden" name="data" id="id_data"> < /p>'
)
self.assertHTMLEqual(
f.as_table(),
' < tr> < td colspan="2"> < ul class="errorlist nonfield">'
' < li>(Hidden field data) This field is required. < /li> < /ul>'
' < input type="hidden" name="data" id="id_data"> < /td> < /tr>'
)
def test_field_named_data(self):