summaryrefslogtreecommitdiff
path: root/tests/forms_tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests/forms_tests')
-rw-r--r--tests/forms_tests/tests/test_error_messages.py16
-rw-r--r--tests/forms_tests/tests/test_fields.py319
-rw-r--r--tests/forms_tests/tests/test_forms.py1093
-rw-r--r--tests/forms_tests/tests/test_formsets.py203
-rw-r--r--tests/forms_tests/tests/test_media.py294
-rw-r--r--tests/forms_tests/tests/test_regressions.py95
-rw-r--r--tests/forms_tests/tests/test_utils.py49
-rw-r--r--tests/forms_tests/tests/test_validators.py6
-rw-r--r--tests/forms_tests/tests/test_widgets.py36
-rw-r--r--tests/forms_tests/tests/tests.py87
10 files changed, 1674 insertions, 524 deletions
diff --git a/tests/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py
index d2a80051ce..0632107e1e 100644
--- a/tests/forms_tests/tests/test_error_messages.py
+++ b/tests/forms_tests/tests/test_error_messages.py
@@ -157,7 +157,11 @@ class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin):
f = URLField(error_messages=e, max_length=17)
self.assertFormErrors(['REQUIRED'], f.clean, '')
self.assertFormErrors(['INVALID'], f.clean, 'abc.c')
- self.assertFormErrors(['"http://djangoproject.com" has more than 17 characters.'], f.clean, 'djangoproject.com')
+ self.assertFormErrors(
+ ['"http://djangoproject.com" has more than 17 characters.'],
+ f.clean,
+ 'djangoproject.com'
+ )
def test_booleanfield(self):
e = {
@@ -226,8 +230,14 @@ class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin):
# This form should print errors the default way.
form1 = TestForm({'first_name': 'John'})
- self.assertHTMLEqual(str(form1['last_name'].errors), '<ul class="errorlist"><li>This field is required.</li></ul>')
- self.assertHTMLEqual(str(form1.errors['__all__']), '<ul class="errorlist nonfield"><li>I like to be awkward.</li></ul>')
+ self.assertHTMLEqual(
+ str(form1['last_name'].errors),
+ '<ul class="errorlist"><li>This field is required.</li></ul>'
+ )
+ self.assertHTMLEqual(
+ str(form1.errors['__all__']),
+ '<ul class="errorlist nonfield"><li>I like to be awkward.</li></ul>'
+ )
# This one should wrap error groups in the customized way.
form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList)
diff --git a/tests/forms_tests/tests/test_fields.py b/tests/forms_tests/tests/test_fields.py
index 6234f5c455..5e4b4269db 100644
--- a/tests/forms_tests/tests/test_fields.py
+++ b/tests/forms_tests/tests/test_fields.py
@@ -117,14 +117,18 @@ class FieldsTests(SimpleTestCase):
f = CharField(max_length=10, required=False)
self.assertEqual('12345', f.clean('12345'))
self.assertEqual('1234567890', f.clean('1234567890'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '1234567890a')
+ msg = "'Ensure this value has at most 10 characters (it has 11).'"
+ with self.assertRaisesMessage(ValidationError, msg):
+ f.clean('1234567890a')
self.assertEqual(f.max_length, 10)
self.assertEqual(f.min_length, None)
def test_charfield_4(self):
f = CharField(min_length=10, required=False)
self.assertEqual('', f.clean(''))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345')
+ msg = "'Ensure this value has at least 10 characters (it has 5).'"
+ with self.assertRaisesMessage(ValidationError, msg):
+ f.clean('12345')
self.assertEqual('1234567890', f.clean('1234567890'))
self.assertEqual('1234567890a', f.clean('1234567890a'))
self.assertEqual(f.max_length, None)
@@ -133,7 +137,9 @@ class FieldsTests(SimpleTestCase):
def test_charfield_5(self):
f = CharField(min_length=10, required=True)
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345')
+ msg = "'Ensure this value has at least 10 characters (it has 5).'"
+ with self.assertRaisesMessage(ValidationError, msg):
+ f.clean('12345')
self.assertEqual('1234567890', f.clean('1234567890'))
self.assertEqual('1234567890a', f.clean('1234567890a'))
self.assertEqual(f.max_length, None)
@@ -327,7 +333,10 @@ class FieldsTests(SimpleTestCase):
f = FloatField(max_value=1.5, min_value=0.5)
self.assertWidgetRendersTo(f, '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" />')
self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6')
- self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value is greater than or equal to 0.5.'",
+ f.clean, '0.4'
+ )
self.assertEqual(1.5, f.clean('1.5'))
self.assertEqual(0.5, f.clean('0.5'))
self.assertEqual(f.max_value, 1.5)
@@ -377,16 +386,34 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean(' 1.0'), Decimal("1.0"))
self.assertEqual(f.clean(' 1.0 '), Decimal("1.0"))
self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a')
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '123.45')
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '1.234')
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 digits before the decimal point.'", f.clean, '123.4')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 4 digits in total.'",
+ f.clean, '123.45'
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 2 decimal places.'",
+ f.clean, '1.234'
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 2 digits before the decimal point.'",
+ f.clean, '123.4'
+ )
self.assertEqual(f.clean('-12.34'), Decimal("-12.34"))
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-123.45')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 4 digits in total.'",
+ f.clean, '-123.45'
+ )
self.assertEqual(f.clean('-.12'), Decimal("-0.12"))
self.assertEqual(f.clean('-00.12'), Decimal("-0.12"))
self.assertEqual(f.clean('-000.12'), Decimal("-0.12"))
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '-000.123')
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-000.12345')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 2 decimal places.'",
+ f.clean, '-000.123'
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 4 digits in total.'",
+ f.clean, '-000.12345'
+ )
self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '--0.12')
self.assertEqual(f.max_digits, 4)
self.assertEqual(f.decimal_places, 2)
@@ -407,7 +434,10 @@ class FieldsTests(SimpleTestCase):
f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5'))
self.assertWidgetRendersTo(f, '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" />')
self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6')
- self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value is greater than or equal to 0.5.'",
+ f.clean, '0.4'
+ )
self.assertEqual(f.clean('1.5'), Decimal("1.5"))
self.assertEqual(f.clean('0.5'), Decimal("0.5"))
self.assertEqual(f.clean('.5'), Decimal("0.5"))
@@ -419,7 +449,10 @@ class FieldsTests(SimpleTestCase):
def test_decimalfield_4(self):
f = DecimalField(decimal_places=2)
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '0.00000001')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 2 decimal places.'",
+ f.clean, '0.00000001'
+ )
def test_decimalfield_5(self):
f = DecimalField(max_digits=3)
@@ -429,13 +462,19 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean('0000000.100'), Decimal("0.100"))
# Only leading whole zeros "collapse" to one digit.
self.assertEqual(f.clean('000000.02'), Decimal('0.02'))
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 3 digits in total.'", f.clean, '000000.0002')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 3 digits in total.'",
+ f.clean, '000000.0002'
+ )
self.assertEqual(f.clean('.002'), Decimal("0.002"))
def test_decimalfield_6(self):
f = DecimalField(max_digits=2, decimal_places=2)
self.assertEqual(f.clean('.01'), Decimal(".01"))
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'", f.clean, '1.1')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'",
+ f.clean, '1.1'
+ )
def test_decimalfield_scientific(self):
f = DecimalField(max_digits=2, decimal_places=2)
@@ -588,8 +627,14 @@ class FieldsTests(SimpleTestCase):
f = DateTimeField()
self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25)))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30)))
- self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)))
- self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)))
+ self.assertEqual(
+ datetime.datetime(2006, 10, 25, 14, 30, 59),
+ f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
+ )
+ self.assertEqual(
+ datetime.datetime(2006, 10, 25, 14, 30, 59, 200),
+ f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
+ )
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.000200'))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.0002'))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('2006-10-25 14:30:45'))
@@ -613,8 +658,14 @@ class FieldsTests(SimpleTestCase):
f = DateTimeField(input_formats=['%Y %m %d %I:%M %p'])
self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25)))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30)))
- self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)))
- self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)))
+ self.assertEqual(
+ datetime.datetime(2006, 10, 25, 14, 30, 59),
+ f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
+ )
+ self.assertEqual(
+ datetime.datetime(2006, 10, 25, 14, 30, 59, 200),
+ f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
+ )
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM'))
self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 14:30:45')
@@ -717,11 +768,22 @@ class FieldsTests(SimpleTestCase):
def test_regexfield_5(self):
f = RegexField('^[0-9]+$', min_length=5, max_length=10)
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", f.clean, '123')
- six.assertRaisesRegex(self, ValidationError, "'Ensure this value has at least 5 characters \(it has 3\)\.', u?'Enter a valid value\.'", f.clean, 'abc')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at least 5 characters (it has 3).'",
+ f.clean, '123'
+ )
+ six.assertRaisesRegex(
+ self, ValidationError,
+ "'Ensure this value has at least 5 characters \(it has 3\)\.',"
+ " u?'Enter a valid value\.'",
+ f.clean, 'abc'
+ )
self.assertEqual('12345', f.clean('12345'))
self.assertEqual('1234567890', f.clean('1234567890'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '12345678901')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 10 characters (it has 11).'",
+ f.clean, '12345678901'
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '12345a')
def test_regexfield_6(self):
@@ -769,9 +831,15 @@ class FieldsTests(SimpleTestCase):
def test_emailfield_min_max_length(self):
f = EmailField(min_length=10, max_length=15)
self.assertWidgetRendersTo(f, '<input id="id_f" type="email" name="f" maxlength="15" />')
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 9).'", f.clean, 'a@foo.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at least 10 characters (it has 9).'",
+ f.clean, 'a@foo.com'
+ )
self.assertEqual('alf@foo.com', f.clean('alf@foo.com'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 15 characters (it has 20).'", f.clean, 'alf123456788@foo.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 15 characters (it has 20).'",
+ f.clean, 'alf123456788@foo.com'
+ )
# FileField ##################################################################
@@ -783,19 +851,43 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None, '')
self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
- self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b''))
- self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b''), '')
+ self.assertRaisesMessage(
+ ValidationError, "'No file was submitted. Check the encoding type on the form.'",
+ f.clean, SimpleUploadedFile('', b'')
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'No file was submitted. Check the encoding type on the form.'",
+ f.clean, SimpleUploadedFile('', b''), ''
+ )
self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf'))
- self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, 'some content that is not a file')
- self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', None))
- self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', b''))
+ self.assertRaisesMessage(
+ ValidationError, "'No file was submitted. Check the encoding type on the form.'",
+ f.clean, 'some content that is not a file'
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'The submitted file is empty.'",
+ f.clean, SimpleUploadedFile('name', None)
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'The submitted file is empty.'",
+ f.clean, SimpleUploadedFile('name', b'')
+ )
self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'))))
- self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8')))))
- self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf')))
+ self.assertIsInstance(
+ f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))),
+ SimpleUploadedFile
+ )
+ self.assertIsInstance(
+ f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf'),
+ SimpleUploadedFile
+ )
def test_filefield_2(self):
f = FileField(max_length=5)
- self.assertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'", f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world'))
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'",
+ f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world')
+ )
self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'))))
@@ -897,8 +989,14 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.alid-.com')
self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.-alid.com')
self.assertEqual('http://valid-----hyphens.com', f.clean('http://valid-----hyphens.com'))
- self.assertEqual('http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah'))
- self.assertEqual('http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804'))
+ self.assertEqual(
+ 'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah',
+ f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah')
+ )
+ self.assertEqual(
+ 'http://www.example.com/s/http://code.djangoproject.com/ticket/13804',
+ f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804')
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '[a')
self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://[a')
@@ -926,9 +1024,15 @@ class FieldsTests(SimpleTestCase):
def test_urlfield_5(self):
f = URLField(min_length=15, max_length=20)
self.assertWidgetRendersTo(f, '<input id="id_f" type="url" name="f" maxlength="20" />')
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 15 characters (it has 12).'", f.clean, 'http://f.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at least 15 characters (it has 12).'",
+ f.clean, 'http://f.com'
+ )
self.assertEqual('http://example.com', f.clean('http://example.com'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 37).'", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 20 characters (it has 37).'",
+ f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com'
+ )
def test_urlfield_6(self):
f = URLField(required=False)
@@ -1033,7 +1137,10 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
self.assertEqual('1', f.clean(1))
self.assertEqual('1', f.clean('1'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, '3'
+ )
def test_choicefield_2(self):
f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
@@ -1041,22 +1148,36 @@ class FieldsTests(SimpleTestCase):
self.assertEqual('', f.clean(None))
self.assertEqual('1', f.clean(1))
self.assertEqual('1', f.clean('1'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, '3'
+ )
def test_choicefield_3(self):
f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
self.assertEqual('J', f.clean('J'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. John is not one of the available choices.'", f.clean, 'John')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. John is not one of the available choices.'",
+ f.clean, 'John'
+ )
def test_choicefield_4(self):
- f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')])
+ f = ChoiceField(
+ choices=[
+ ('Numbers', (('1', 'One'), ('2', 'Two'))),
+ ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other'),
+ ]
+ )
self.assertEqual('1', f.clean(1))
self.assertEqual('1', f.clean('1'))
self.assertEqual('3', f.clean(3))
self.assertEqual('3', f.clean('3'))
self.assertEqual('5', f.clean(5))
self.assertEqual('5', f.clean('5'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, '6')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 6 is not one of the available choices.'",
+ f.clean, '6'
+ )
def test_choicefield_callable(self):
choices = lambda: [('J', 'John'), ('P', 'Paul')]
@@ -1093,7 +1214,10 @@ class FieldsTests(SimpleTestCase):
def test_typedchoicefield_1(self):
f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual(1, f.clean('1'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, '2')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 2 is not one of the available choices.'",
+ f.clean, '2'
+ )
def test_typedchoicefield_2(self):
# Different coercion, same validation.
@@ -1109,7 +1233,10 @@ class FieldsTests(SimpleTestCase):
# Even more weirdness: if you have a valid choice but your coercion function
# can't coerce, you'll still get a validation error. Don't do this!
f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, 'B')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. B is not one of the available choices.'",
+ f.clean, 'B'
+ )
# Required fields require values
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
@@ -1140,11 +1267,14 @@ class FieldsTests(SimpleTestCase):
f = TypedChoiceField(choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True)
self.assertEqual(Decimal('1.2'), f.clean('2'))
- self.assertRaisesMessage(ValidationError,
- "'This field is required.'", f.clean, '')
- self.assertRaisesMessage(ValidationError,
- "'Select a valid choice. 3 is not one of the available choices.'",
- f.clean, '3')
+ self.assertRaisesMessage(
+ ValidationError, "'This field is required.'",
+ f.clean, ''
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, '3'
+ )
# NullBooleanField ############################################################
@@ -1168,7 +1298,11 @@ class FieldsTests(SimpleTestCase):
hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True)
hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False)
f = HiddenNullBooleanForm()
- self.assertHTMLEqual('<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1" /><input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2" />', str(f))
+ self.assertHTMLEqual(
+ '<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1" />'
+ '<input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2" />',
+ str(f)
+ )
def test_nullbooleanfield_3(self):
class HiddenNullBooleanForm(Form):
@@ -1218,7 +1352,10 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, [])
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ())
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, ['3']
+ )
def test_multiplechoicefield_2(self):
f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
@@ -1232,18 +1369,29 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
self.assertEqual([], f.clean([]))
self.assertEqual([], f.clean(()))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, ['3']
+ )
def test_multiplechoicefield_3(self):
- f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')])
+ f = MultipleChoiceField(
+ choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')]
+ )
self.assertEqual(['1'], f.clean([1]))
self.assertEqual(['1'], f.clean(['1']))
self.assertEqual(['1', '5'], f.clean([1, 5]))
self.assertEqual(['1', '5'], f.clean([1, '5']))
self.assertEqual(['1', '5'], f.clean(['1', 5]))
self.assertEqual(['1', '5'], f.clean(['1', '5']))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['6'])
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['1', '6'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 6 is not one of the available choices.'",
+ f.clean, ['6']
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 6 is not one of the available choices.'",
+ f.clean, ['1', '6']
+ )
def test_multiplechoicefield_changed(self):
f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')])
@@ -1262,7 +1410,10 @@ class FieldsTests(SimpleTestCase):
def test_typedmultiplechoicefield_1(self):
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual([1], f.clean(['1']))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['2'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 2 is not one of the available choices.'",
+ f.clean, ['2']
+ )
def test_typedmultiplechoicefield_2(self):
# Different coercion, same validation.
@@ -1277,13 +1428,19 @@ class FieldsTests(SimpleTestCase):
def test_typedmultiplechoicefield_4(self):
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual([1, -1], f.clean(['1', '-1']))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['1', '2'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 2 is not one of the available choices.'",
+ f.clean, ['1', '2']
+ )
def test_typedmultiplechoicefield_5(self):
# Even more weirdness: if you have a valid choice but your coercion function
# can't coerce, you'll still get a validation error. Don't do this!
f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, ['B'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. B is not one of the available choices.'",
+ f.clean, ['B']
+ )
# Required fields require values
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, [])
@@ -1324,7 +1481,10 @@ class FieldsTests(SimpleTestCase):
def test_combofield_1(self):
f = ComboField(fields=[CharField(max_length=20), EmailField()])
self.assertEqual('test@example.com', f.clean('test@example.com'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 20 characters (it has 28).'",
+ f.clean, 'longemailaddress@example.com'
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
@@ -1332,7 +1492,10 @@ class FieldsTests(SimpleTestCase):
def test_combofield_2(self):
f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False)
self.assertEqual('test@example.com', f.clean('test@example.com'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 20 characters (it has 28).'",
+ f.clean, 'longemailaddress@example.com'
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email')
self.assertEqual('', f.clean(''))
self.assertEqual('', f.clean(None))
@@ -1362,7 +1525,10 @@ class FieldsTests(SimpleTestCase):
for exp, got in zip(expected, fix_os_paths(f.choices)):
self.assertEqual(exp[1], got[1])
self.assertTrue(got[0].endswith(exp[0]))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. fields.py is not one of the available choices.'", f.clean, 'fields.py')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. fields.py is not one of the available choices.'",
+ f.clean, 'fields.py'
+ )
assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py')
def test_filepathfield_3(self):
@@ -1437,24 +1603,36 @@ class FieldsTests(SimpleTestCase):
from django.forms.widgets import SplitDateTimeWidget
f = SplitDateTimeField()
self.assertIsInstance(f.widget, SplitDateTimeWidget)
- self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]))
+ self.assertEqual(
+ datetime.datetime(2006, 1, 10, 7, 30),
+ f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])
+ )
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
- six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'])
+ six.assertRaisesRegex(
+ self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'",
+ f.clean, ['hello', 'there']
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there'])
self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30'])
def test_splitdatetimefield_2(self):
f = SplitDateTimeField(required=False)
- self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]))
+ self.assertEqual(
+ datetime.datetime(2006, 1, 10, 7, 30),
+ f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])
+ )
self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean(['2006-01-10', '07:30']))
self.assertIsNone(f.clean(None))
self.assertIsNone(f.clean(''))
self.assertIsNone(f.clean(['']))
self.assertIsNone(f.clean(['', '']))
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
- six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'])
+ six.assertRaisesRegex(
+ self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'",
+ f.clean, ['hello', 'there']
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there'])
self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30'])
self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', ''])
@@ -1489,7 +1667,10 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4')
- self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, 'foo::223:6cff:fe8a:2e8a')
+ self.assertRaisesMessage(
+ ValidationError, "'This is not a valid IPv6 address.'",
+ f.clean, 'foo::223:6cff:fe8a:2e8a'
+ )
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2')
@@ -1518,7 +1699,10 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4')
- self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, 'foo::223:6cff:fe8a:2e8a')
+ self.assertRaisesMessage(
+ ValidationError, "'This is not a valid IPv6 address.'",
+ f.clean, 'foo::223:6cff:fe8a:2e8a'
+ )
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2')
@@ -1535,7 +1719,10 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4')
- self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, 'foo::223:6cff:fe8a:2e8a')
+ self.assertRaisesMessage(
+ ValidationError, "'This is not a valid IPv6 address.'",
+ f.clean, 'foo::223:6cff:fe8a:2e8a'
+ )
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2')
diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
index d8cdabae2d..ac96d775a2 100644
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -58,9 +58,18 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(p.cleaned_data["first_name"], 'John')
self.assertEqual(p.cleaned_data["last_name"], 'Lennon')
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
- self.assertHTMLEqual(str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" />')
- self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" />')
- self.assertHTMLEqual(str(p['birthday']), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />')
+ self.assertHTMLEqual(
+ str(p['first_name']),
+ '<input type="text" name="first_name" value="John" id="id_first_name" />'
+ )
+ self.assertHTMLEqual(
+ str(p['last_name']),
+ '<input type="text" name="last_name" value="Lennon" id="id_last_name" />'
+ )
+ self.assertHTMLEqual(
+ str(p['birthday']),
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />'
+ )
nonexistenterror = "Key u?'nonexistentfield' not found in 'Person'"
with six.assertRaisesRegex(self, KeyError, nonexistenterror):
@@ -72,9 +81,12 @@ class FormsTestCase(SimpleTestCase):
for boundfield in p:
form_output.append(str(boundfield))
- self.assertHTMLEqual('\n'.join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" />
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<input type="text" name="first_name" value="John" id="id_first_name" />
<input type="text" name="last_name" value="Lennon" id="id_last_name" />
-<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />""")
+<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />"""
+ )
form_output = []
@@ -86,9 +98,15 @@ class FormsTestCase(SimpleTestCase):
['Last name', 'Lennon'],
['Birthday', '1940-10-9']
])
- self.assertHTMLEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>""")
+ self.assertHTMLEqual(
+ str(p),
+ """<tr><th><label for="id_first_name">First name:</label></th><td>
+<input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>
+<tr><th><label for="id_last_name">Last name:</label></th><td>
+<input type="text" name="last_name" value="Lennon" id="id_last_name" /></td></tr>
+<tr><th><label for="id_birthday">Birthday:</label></th><td>
+<input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>"""
+ )
def test_empty_dict(self):
# Empty dictionaries are valid, too.
@@ -99,21 +117,54 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(p.errors['birthday'], ['This field is required.'])
self.assertFalse(p.is_valid())
self.assertEqual(p.cleaned_data, {})
- self.assertHTMLEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
- self.assertHTMLEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
- self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""")
- self.assertHTMLEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul>
-<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
+ self.assertHTMLEqual(
+ str(p),
+ """<tr><th><label for="id_first_name">First name:</label></th><td>
+<ul class="errorlist"><li>This field is required.</li></ul>
+<input type="text" name="first_name" id="id_first_name" /></td></tr>
+<tr><th><label for="id_last_name">Last name:</label></th>
+<td><ul class="errorlist"><li>This field is required.</li></ul>
+<input type="text" name="last_name" id="id_last_name" /></td></tr>
+<tr><th><label for="id_birthday">Birthday:</label></th><td>
+<ul class="errorlist"><li>This field is required.</li></ul>
+<input type="text" name="birthday" id="id_birthday" /></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ p.as_table(),
+ """<tr><th><label for="id_first_name">First name:</label></th><td>
+<ul class="errorlist"><li>This field is required.</li></ul>
+<input type="text" name="first_name" id="id_first_name" /></td></tr>
+<tr><th><label for="id_last_name">Last name:</label></th>
+<td><ul class="errorlist"><li>This field is required.</li></ul>
+<input type="text" name="last_name" id="id_last_name" /></td></tr>
+<tr><th><label for="id_birthday">Birthday:</label></th>
+<td><ul class="errorlist"><li>This field is required.</li></ul>
+<input type="text" name="birthday" id="id_birthday" /></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><ul class="errorlist"><li>This field is required.</li></ul>
+<label for="id_first_name">First name:</label>
+<input type="text" name="first_name" id="id_first_name" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+<label for="id_last_name">Last name:</label>
+<input type="text" name="last_name" id="id_last_name" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+<label for="id_birthday">Birthday:</label>
+<input type="text" name="birthday" id="id_birthday" /></li>"""
+ )
+ self.assertHTMLEqual(
+ p.as_p(),
+ """<ul class="errorlist"><li>This field is required.</li></ul>
+<p><label for="id_first_name">First name:</label>
+<input type="text" name="first_name" id="id_first_name" /></p>
<ul class="errorlist"><li>This field is required.</li></ul>
-<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
+<p><label for="id_last_name">Last name:</label>
+<input type="text" name="last_name" id="id_last_name" /></p>
<ul class="errorlist"><li>This field is required.</li></ul>
-<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
+<p><label for="id_birthday">Birthday:</label>
+<input type="text" name="birthday" id="id_birthday" /></p>"""
+ )
def test_unbound_form(self):
# If you don't pass any values to the Form's __init__(), or if you pass None,
@@ -128,34 +179,96 @@ class FormsTestCase(SimpleTestCase):
self.fail('Attempts to access cleaned_data when validation fails should fail.')
except AttributeError:
pass
- self.assertHTMLEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
- self.assertHTMLEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
- self.assertHTMLEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
-<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
-<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""")
- self.assertHTMLEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
-<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
-<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
+ self.assertHTMLEqual(
+ str(p),
+ """<tr><th><label for="id_first_name">First name:</label></th><td>
+<input type="text" name="first_name" id="id_first_name" /></td></tr>
+<tr><th><label for="id_last_name">Last name:</label></th><td>
+<input type="text" name="last_name" id="id_last_name" /></td></tr>
+<tr><th><label for="id_birthday">Birthday:</label></th><td>
+<input type="text" name="birthday" id="id_birthday" /></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ p.as_table(),
+ """<tr><th><label for="id_first_name">First name:</label></th><td>
+<input type="text" name="first_name" id="id_first_name" /></td></tr>
+<tr><th><label for="id_last_name">Last name:</label></th><td>
+<input type="text" name="last_name" id="id_last_name" /></td></tr>
+<tr><th><label for="id_birthday">Birthday:</label></th><td>
+<input type="text" name="birthday" id="id_birthday" /></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><label for="id_first_name">First name:</label>
+<input type="text" name="first_name" id="id_first_name" /></li>
+<li><label for="id_last_name">Last name:</label>
+<input type="text" name="last_name" id="id_last_name" /></li>
+<li><label for="id_birthday">Birthday:</label>
+<input type="text" name="birthday" id="id_birthday" /></li>"""
+ )
+ self.assertHTMLEqual(
+ p.as_p(),
+ """<p><label for="id_first_name">First name:</label>
+<input type="text" name="first_name" id="id_first_name" /></p>
+<p><label for="id_last_name">Last name:</label>
+<input type="text" name="last_name" id="id_last_name" /></p>
+<p><label for="id_birthday">Birthday:</label>
+<input type="text" name="birthday" id="id_birthday" /></p>"""
+ )
def test_unicode_values(self):
# Unicode values are handled properly.
- p = Person({'first_name': 'John', 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'})
- self.assertHTMLEqual(p.as_table(), '<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>\n<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></td></tr>\n<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>')
- self.assertHTMLEqual(p.as_ul(), '<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></li>\n<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></li>\n<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></li>')
- self.assertHTMLEqual(p.as_p(), '<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>')
+ p = Person({
+ 'first_name': 'John',
+ 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111',
+ 'birthday': '1940-10-9'
+ })
+ self.assertHTMLEqual(
+ p.as_table(),
+ '<tr><th><label for="id_first_name">First name:</label></th><td>'
+ '<input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>\n'
+ '<tr><th><label for="id_last_name">Last name:</label>'
+ '</th><td><input type="text" name="last_name" '
+ 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"'
+ 'id="id_last_name" /></td></tr>\n'
+ '<tr><th><label for="id_birthday">Birthday:</label></th><td>'
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>'
+ )
+ self.assertHTMLEqual(
+ p.as_ul(),
+ '<li><label for="id_first_name">First name:</label> '
+ '<input type="text" name="first_name" value="John" id="id_first_name" /></li>\n'
+ '<li><label for="id_last_name">Last name:</label> '
+ '<input type="text" name="last_name" '
+ 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></li>\n'
+ '<li><label for="id_birthday">Birthday:</label> '
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></li>'
+ )
+ self.assertHTMLEqual(
+ p.as_p(),
+ '<p><label for="id_first_name">First name:</label> '
+ '<input type="text" name="first_name" value="John" id="id_first_name" /></p>\n'
+ '<p><label for="id_last_name">Last name:</label> '
+ '<input type="text" name="last_name" '
+ 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n'
+ '<p><label for="id_birthday">Birthday:</label> '
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>'
+ )
p = Person({'last_name': 'Lennon'})
self.assertEqual(p.errors['first_name'], ['This field is required.'])
self.assertEqual(p.errors['birthday'], ['This field is required.'])
self.assertFalse(p.is_valid())
- self.assertDictEqual(p.errors, {'birthday': ['This field is required.'], 'first_name': ['This field is required.']})
+ self.assertDictEqual(
+ p.errors,
+ {'birthday': ['This field is required.'], 'first_name': ['This field is required.']}
+ )
self.assertEqual(p.cleaned_data, {'last_name': 'Lennon'})
self.assertEqual(p['first_name'].errors, ['This field is required.'])
- self.assertHTMLEqual(p['first_name'].errors.as_ul(), '<ul class="errorlist"><li>This field is required.</li></ul>')
+ self.assertHTMLEqual(
+ p['first_name'].errors.as_ul(),
+ '<ul class="errorlist"><li>This field is required.</li></ul>'
+ )
self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.')
p = Person()
@@ -168,7 +281,13 @@ class FormsTestCase(SimpleTestCase):
# Form, even if you pass extra data when you define the Form. In this
# example, we pass a bunch of extra fields to the form constructor,
# but cleaned_data contains only the form's fields.
- data = {'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9', 'extra1': 'hello', 'extra2': 'hello'}
+ data = {
+ 'first_name': 'John',
+ 'last_name': 'Lennon',
+ 'birthday': '1940-10-9',
+ 'extra1': 'hello',
+ 'extra2': 'hello',
+ }
p = Person(data)
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data['first_name'], 'John')
@@ -212,47 +331,84 @@ class FormsTestCase(SimpleTestCase):
# into which the field's name will be inserted. It will also put a <label> around
# the human-readable labels for a field.
p = Person(auto_id='%s_id')
- self.assertHTMLEqual(p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td><input type="text" name="first_name" id="first_name_id" /></td></tr>
-<tr><th><label for="last_name_id">Last name:</label></th><td><input type="text" name="last_name" id="last_name_id" /></td></tr>
-<tr><th><label for="birthday_id">Birthday:</label></th><td><input type="text" name="birthday" id="birthday_id" /></td></tr>""")
- self.assertHTMLEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></li>
-<li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></li>
-<li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></li>""")
- self.assertHTMLEqual(p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></p>
-<p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></p>
-<p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></p>""")
+ self.assertHTMLEqual(
+ p.as_table(),
+ """<tr><th><label for="first_name_id">First name:</label></th><td>
+<input type="text" name="first_name" id="first_name_id" /></td></tr>
+<tr><th><label for="last_name_id">Last name:</label></th><td>
+<input type="text" name="last_name" id="last_name_id" /></td></tr>
+<tr><th><label for="birthday_id">Birthday:</label></th><td>
+<input type="text" name="birthday" id="birthday_id" /></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><label for="first_name_id">First name:</label>
+<input type="text" name="first_name" id="first_name_id" /></li>
+<li><label for="last_name_id">Last name:</label>
+<input type="text" name="last_name" id="last_name_id" /></li>
+<li><label for="birthday_id">Birthday:</label>
+<input type="text" name="birthday" id="birthday_id" /></li>"""
+ )
+ self.assertHTMLEqual(
+ p.as_p(),
+ """<p><label for="first_name_id">First name:</label>
+<input type="text" name="first_name" id="first_name_id" /></p>
+<p><label for="last_name_id">Last name:</label>
+<input type="text" name="last_name" id="last_name_id" /></p>
+<p><label for="birthday_id">Birthday:</label>
+<input type="text" name="birthday" id="birthday_id" /></p>"""
+ )
def test_auto_id_true(self):
# If auto_id is any True value whose str() does not contain '%s', the "id"
# attribute will be the name of the field.
p = Person(auto_id=True)
- self.assertHTMLEqual(p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" /></li>
-<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
-<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><label for="first_name">First name:</label>
+<input type="text" name="first_name" id="first_name" /></li>
+<li><label for="last_name">Last name:</label>
+<input type="text" name="last_name" id="last_name" /></li>
+<li><label for="birthday">Birthday:</label>
+<input type="text" name="birthday" id="birthday" /></li>"""
+ )
def test_auto_id_false(self):
# If auto_id is any False value, an "id" attribute won't be output unless it
# was manually entered.
p = Person(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>First name: <input type="text" name="first_name" /></li>
<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /></li>""")
+<li>Birthday: <input type="text" name="birthday" /></li>"""
+ )
def test_id_on_field(self):
# In this example, auto_id is False, but the "id" attribute for the "first_name"
# field is given. Also note that field gets a <label>, while the others don't.
p = PersonNew(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li>
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><label for="first_name_id">First name:</label>
+<input type="text" id="first_name_id" name="first_name" /></li>
<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /></li>""")
+<li>Birthday: <input type="text" name="birthday" /></li>"""
+ )
def test_auto_id_on_form_and_field(self):
# If the "id" attribute is specified in the Form and auto_id is True, the "id"
# attribute in the Form gets precedence.
p = PersonNew(auto_id=True)
- self.assertHTMLEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li>
-<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
-<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><label for="first_name_id">First name:</label>
+<input type="text" id="first_name_id" name="first_name" /></li>
+<li><label for="last_name">Last name:</label>
+<input type="text" name="last_name" id="last_name" /></li>
+<li><label for="birthday">Birthday:</label>
+<input type="text" name="birthday" id="birthday" /></li>"""
+ )
def test_various_boolean_values(self):
class SignupForm(Form):
@@ -314,7 +470,10 @@ class FormsTestCase(SimpleTestCase):
# as_hidden():
self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" />')
f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
- self.assertHTMLEqual(f['subject'].as_textarea(), '<textarea rows="10" cols="40" name="subject">Hello</textarea>')
+ self.assertHTMLEqual(
+ f['subject'].as_textarea(),
+ '<textarea rows="10" cols="40" name="subject">Hello</textarea>'
+ )
self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" value="I love you." />')
self.assertHTMLEqual(f['message'].as_hidden(), '<input type="hidden" name="message" value="I love you." />')
@@ -369,7 +528,10 @@ class FormsTestCase(SimpleTestCase):
# defined on the Field, not the ones defined on the Widget.
class FrameworkForm(Form):
name = CharField()
- language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}))
+ language = ChoiceField(
+ choices=[('P', 'Python'), ('J', 'Java')],
+ widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}),
+ )
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language">
@@ -422,50 +584,74 @@ class FormsTestCase(SimpleTestCase):
# gets a distinct ID, formed by appending an underscore plus the button's
# zero-based index.
f = FrameworkForm(auto_id='id_%s')
- self.assertHTMLEqual(str(f['language']), """<ul id="id_language">
+ self.assertHTMLEqual(
+ str(f['language']),
+ """<ul id="id_language">
<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
-</ul>""")
+</ul>"""
+ )
# When RadioSelect is used with auto_id, and the whole form is printed using
# either as_table() or as_ul(), the label for the RadioSelect will point to the
# ID of the *first* radio button.
- self.assertHTMLEqual(f.as_table(), """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" /></td></tr>
+ self.assertHTMLEqual(
+ f.as_table(),
+ """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" /></td></tr>
<tr><th><label for="id_language_0">Language:</label></th><td><ul id="id_language">
<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
-</ul></td></tr>""")
- self.assertHTMLEqual(f.as_ul(), """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li>
+</ul></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ f.as_ul(),
+ """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li>
<li><label for="id_language_0">Language:</label> <ul id="id_language">
<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
-</ul></li>""")
- self.assertHTMLEqual(f.as_p(), """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
+</ul></li>"""
+ )
+ self.assertHTMLEqual(
+ f.as_p(),
+ """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
<p><label for="id_language_0">Language:</label> <ul id="id_language">
<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
-</ul></p>""")
+</ul></p>"""
+ )
# Test iterating on individual radios in a template
t = Template('{% for radio in form.language %}<div class="myradio">{{ radio }}</div>{% endfor %}')
- self.assertHTMLEqual(t.render(Context({'form': f})), """<div class="myradio"><label for="id_language_0">
+ self.assertHTMLEqual(
+ t.render(Context({'form': f})),
+ """<div class="myradio"><label for="id_language_0">
<input id="id_language_0" name="language" type="radio" value="P" /> Python</label></div>
<div class="myradio"><label for="id_language_1">
-<input id="id_language_1" name="language" type="radio" value="J" /> Java</label></div>""")
+<input id="id_language_1" name="language" type="radio" value="J" /> Java</label></div>"""
+ )
def test_form_with_iterable_boundfield(self):
class BeatleForm(Form):
- name = ChoiceField(choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], widget=RadioSelect)
+ name = ChoiceField(
+ choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')],
+ widget=RadioSelect,
+ )
f = BeatleForm(auto_id=False)
- self.assertHTMLEqual('\n'.join(str(bf) for bf in f['name']), """<label><input type="radio" name="name" value="john" /> John</label>
+ self.assertHTMLEqual(
+ '\n'.join(str(bf) for bf in f['name']),
+ """<label><input type="radio" name="name" value="john" /> John</label>
<label><input type="radio" name="name" value="paul" /> Paul</label>
<label><input type="radio" name="name" value="george" /> George</label>
-<label><input type="radio" name="name" value="ringo" /> Ringo</label>""")
- self.assertHTMLEqual('\n'.join('<div>%s</div>' % bf for bf in f['name']), """<div><label><input type="radio" name="name" value="john" /> John</label></div>
+<label><input type="radio" name="name" value="ringo" /> Ringo</label>"""
+ )
+ self.assertHTMLEqual(
+ '\n'.join('<div>%s</div>' % bf for bf in f['name']),
+ """<div><label><input type="radio" name="name" value="john" /> John</label></div>
<div><label><input type="radio" name="name" value="paul" /> Paul</label></div>
<div><label><input type="radio" name="name" value="george" /> George</label></div>
-<div><label><input type="radio" name="name" value="ringo" /> Ringo</label></div>""")
+<div><label><input type="radio" name="name" value="ringo" /> Ringo</label></div>"""
+ )
def test_form_with_noniterable_boundfield(self):
# You can iterate over any BoundField, not just those with widget=RadioSelect.
@@ -552,14 +738,25 @@ class FormsTestCase(SimpleTestCase):
f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'})
self.assertTrue(f.is_valid())
- self.assertHTMLEqual(str(f['when']), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" /><input type="text" name="when_1" value="01:01" id="id_when_1" />')
- self.assertHTMLEqual(f['when'].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0" /><input type="hidden" name="when_1" value="01:01" id="id_when_1" />')
+ self.assertHTMLEqual(
+ str(f['when']),
+ '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" />'
+ '<input type="text" name="when_1" value="01:01" id="id_when_1" />'
+ )
+ self.assertHTMLEqual(
+ f['when'].as_hidden(),
+ '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0" />'
+ '<input type="hidden" name="when_1" value="01:01" id="id_when_1" />'
+ )
def test_mulitple_choice_checkbox(self):
# MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
class SongForm(Form):
name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
+ composers = MultipleChoiceField(
+ choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
+ widget=CheckboxSelectMultiple,
+ )
f = SongForm(auto_id=False)
self.assertHTMLEqual(str(f['composers']), """<ul>
@@ -589,20 +786,31 @@ class FormsTestCase(SimpleTestCase):
# zero-based index.
class SongForm(Form):
name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
+ composers = MultipleChoiceField(
+ choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
+ widget=CheckboxSelectMultiple,
+ )
f = SongForm(auto_id='%s_id')
- self.assertHTMLEqual(str(f['composers']), """<ul id="composers_id">
-<li><label for="composers_id_0"><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
-<li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
-</ul>""")
+ self.assertHTMLEqual(
+ str(f['composers']),
+ """<ul id="composers_id">
+<li><label for="composers_id_0">
+<input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
+<li><label for="composers_id_1">
+<input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
+</ul>"""
+ )
def test_multiple_choice_list_data(self):
# Data for a MultipleChoiceField should be a list. QueryDict and
# MultiValueDict conveniently work with this.
class SongForm(Form):
name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
+ composers = MultipleChoiceField(
+ choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
+ widget=CheckboxSelectMultiple,
+ )
data = {'name': 'Yesterday', 'composers': ['J', 'P']}
f = SongForm(data)
@@ -619,16 +827,26 @@ class FormsTestCase(SimpleTestCase):
def test_multiple_hidden(self):
class SongForm(Form):
name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
+ composers = MultipleChoiceField(
+ choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
+ widget=CheckboxSelectMultiple,
+ )
# The MultipleHiddenInput widget renders multiple values as hidden fields.
class SongFormHidden(Form):
name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput)
+ composers = MultipleChoiceField(
+ choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
+ widget=MultipleHiddenInput,
+ )
f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
- self.assertHTMLEqual(f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" /><input type="hidden" name="composers" value="J" />
-<input type="hidden" name="composers" value="P" /></li>""")
+ self.assertHTMLEqual(
+ f.as_ul(),
+ """<li>Name: <input type="text" name="name" value="Yesterday" />
+<input type="hidden" name="composers" value="J" />
+<input type="hidden" name="composers" value="P" /></li>"""
+ )
# When using CheckboxSelectMultiple, the framework expects a list of input and
# returns a list of input.
@@ -653,17 +871,39 @@ class FormsTestCase(SimpleTestCase):
raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name'])
def clean_special_safe_name(self):
- raise ValidationError(mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name']))
+ raise ValidationError(
+ mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name'])
+ )
- f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False)
- self.assertHTMLEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Nothing to escape&#39;</li></ul><input type="text" name="special_name" value="Nothing to escape" /></td></tr>
-<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="Nothing to escape" /></td></tr>""")
+ f = EscapingForm({
+ 'special_name':
+ "Nothing to escape",
+ 'special_safe_name': "Nothing to escape",
+ }, auto_id=False)
+ self.assertHTMLEqual(
+ f.as_table(),
+ """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
+<ul class="errorlist"><li>Something&#39;s wrong with &#39;Nothing to escape&#39;</li></ul>
+<input type="text" name="special_name" value="Nothing to escape" /></td></tr>
+<tr><th><em>Special</em> Field:</th><td>
+<ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul>
+<input type="text" name="special_safe_name" value="Nothing to escape" /></td></tr>"""
+ )
f = EscapingForm({
'special_name': "Should escape < & > and <script>alert('xss')</script>",
'special_safe_name': "<i>Do not escape</i>"
}, auto_id=False)
- self.assertHTMLEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;&#39;</li></ul><input type="text" name="special_name" value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;" /></td></tr>
-<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="&lt;i&gt;Do not escape&lt;/i&gt;" /></td></tr>""")
+ self.assertHTMLEqual(
+ f.as_table(),
+ """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
+<ul class="errorlist"><li>Something&#39;s wrong with &#39;Should escape &lt; &amp; &gt; and
+&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;&#39;</li></ul>
+<input type="text" name="special_name"
+value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;" /></td></tr>
+<tr><th><em>Special</em> Field:</th><td>
+<ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>
+<input type="text" name="special_safe_name" value="&lt;i&gt;Do not escape&lt;/i&gt;" /></td></tr>"""
+ )
def test_validating_multiple_fields(self):
# There are a couple of ways to do multiple-field validation. If you want the
@@ -679,7 +919,8 @@ class FormsTestCase(SimpleTestCase):
password2 = CharField(widget=PasswordInput)
def clean_password2(self):
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2')
+ and self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
return self.cleaned_data['password2']
@@ -717,7 +958,8 @@ class FormsTestCase(SimpleTestCase):
def clean(self):
# Test raising a ValidationError as NON_FIELD_ERRORS.
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2')
+ and self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
# Test raising ValidationError that targets multiple fields.
@@ -743,23 +985,38 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(f.errors, {})
f = UserRegistration({}, auto_id=False)
- self.assertHTMLEqual(f.as_table(), """<tr><th>Username:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="username" maxlength="10" /></td></tr>
-<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr>
-<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr>""")
+ self.assertHTMLEqual(
+ f.as_table(),
+ """<tr><th>Username:</th><td>
+<ul class="errorlist"><li>This field is required.</li></ul>
+<input type="text" name="username" maxlength="10" /></td></tr>
+<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
+<input type="password" name="password1" /></td></tr>
+<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
+<input type="password" name="password2" /></td></tr>"""
+ )
self.assertEqual(f.errors['username'], ['This field is required.'])
self.assertEqual(f.errors['password1'], ['This field is required.'])
self.assertEqual(f.errors['password2'], ['This field is required.'])
f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
self.assertEqual(f.errors['__all__'], ['Please make sure your passwords match.'])
- self.assertHTMLEqual(f.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr>
+ self.assertHTMLEqual(
+ f.as_table(),
+ """<tr><td colspan="2">
+<ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr>
<tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr>
<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
-<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>""")
- self.assertHTMLEqual(f.as_ul(), """<li><ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></li>
+<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ f.as_ul(),
+ """<li><ul class="errorlist nonfield">
+<li>Please make sure your passwords match.</li></ul></li>
<li>Username: <input type="text" name="username" value="adrian" maxlength="10" /></li>
<li>Password1: <input type="password" name="password1" /></li>
-<li>Password2: <input type="password" name="password2" /></li>""")
+<li>Password2: <input type="password" name="password2" /></li>"""
+ )
f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
self.assertEqual(f.errors, {})
@@ -767,11 +1024,19 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(f.cleaned_data['password1'], 'foo')
self.assertEqual(f.cleaned_data['password2'], 'foo')
- f = UserRegistration({'username': 'adrian', 'password1': 'FORBIDDEN_VALUE', 'password2': 'FORBIDDEN_VALUE'}, auto_id=False)
+ f = UserRegistration({
+ 'username': 'adrian',
+ 'password1': 'FORBIDDEN_VALUE',
+ 'password2': 'FORBIDDEN_VALUE',
+ }, auto_id=False)
self.assertEqual(f.errors['password1'], ['Forbidden value.'])
self.assertEqual(f.errors['password2'], ['Forbidden value.'])
- f = UserRegistration({'username': 'adrian', 'password1': 'FORBIDDEN_VALUE2', 'password2': 'FORBIDDEN_VALUE2'}, auto_id=False)
+ f = UserRegistration({
+ 'username': 'adrian',
+ 'password1': 'FORBIDDEN_VALUE2',
+ 'password2': 'FORBIDDEN_VALUE2',
+ }, auto_id=False)
self.assertEqual(f.errors['__all__'], ['Non-field error 1.', 'Non-field error 2.'])
self.assertEqual(f.errors['password1'], ['Forbidden value 2.'])
self.assertEqual(f.errors['password2'], ['Forbidden value 2.'])
@@ -872,9 +1137,12 @@ class FormsTestCase(SimpleTestCase):
self.fields['birthday'] = DateField()
p = Person(auto_id=False)
- self.assertHTMLEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
+ self.assertHTMLEqual(
+ p.as_table(),
+ """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr>""")
+<tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr>"""
+ )
# Instances of a dynamic Form do not persist fields from one Form instance to
# the next.
@@ -887,12 +1155,18 @@ class FormsTestCase(SimpleTestCase):
field_list = [('field1', CharField()), ('field2', CharField())]
my_form = MyForm(field_list=field_list)
- self.assertHTMLEqual(my_form.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
+ self.assertHTMLEqual(
+ my_form.as_table(),
+ """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
+<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>"""
+ )
field_list = [('field3', CharField()), ('field4', CharField())]
my_form = MyForm(field_list=field_list)
- self.assertHTMLEqual(my_form.as_table(), """<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
+ self.assertHTMLEqual(
+ my_form.as_table(),
+ """<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
+<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>"""
+ )
class MyForm(Form):
default_field_1 = CharField()
@@ -906,16 +1180,22 @@ class FormsTestCase(SimpleTestCase):
field_list = [('field1', CharField()), ('field2', CharField())]
my_form = MyForm(field_list=field_list)
- self.assertHTMLEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
+ self.assertHTMLEqual(
+ my_form.as_table(),
+ """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
+<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>"""
+ )
field_list = [('field3', CharField()), ('field4', CharField())]
my_form = MyForm(field_list=field_list)
- self.assertHTMLEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
+ self.assertHTMLEqual(
+ my_form.as_table(),
+ """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
+<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>"""
+ )
# Similarly, changes to field attributes do not persist from one Form instance
# to the next.
@@ -937,7 +1217,11 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
f = Person(names_required=True)
self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True))
- self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'required'}, {'class': 'required'}))
+ self.assertEqual(
+ f['first_name'].field.widget.attrs,
+ f['last_name'].field.widget.attrs,
+ ({'class': 'reuired'}, {'class': 'required'})
+ )
f = Person(names_required=False)
self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
@@ -1006,45 +1290,87 @@ class FormsTestCase(SimpleTestCase):
birthday = DateField()
p = Person(auto_id=False)
- self.assertHTMLEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
+ self.assertHTMLEqual(
+ p.as_table(),
+ """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr>""")
- self.assertHTMLEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
+<tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>First name: <input type="text" name="first_name" /></li>
<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li>""")
- self.assertHTMLEqual(p.as_p(), """<p>First name: <input type="text" name="first_name" /></p>
+<li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li>"""
+ )
+ self.assertHTMLEqual(
+ p.as_p(), """<p>First name: <input type="text" name="first_name" /></p>
<p>Last name: <input type="text" name="last_name" /></p>
-<p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p>""")
+<p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p>"""
+ )
# With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
p = Person(auto_id='id_%s')
- self.assertHTMLEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr>""")
- self.assertHTMLEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
-<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
-<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></li>""")
- self.assertHTMLEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
-<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
-<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></p>""")
+ self.assertHTMLEqual(
+ p.as_table(),
+ """<tr><th><label for="id_first_name">First name:</label></th><td>
+<input type="text" name="first_name" id="id_first_name" /></td></tr>
+<tr><th><label for="id_last_name">Last name:</label></th><td>
+<input type="text" name="last_name" id="id_last_name" /></td></tr>
+<tr><th><label for="id_birthday">Birthday:</label></th><td>
+<input type="text" name="birthday" id="id_birthday" />
+<input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><label for="id_first_name">First name:</label>
+<input type="text" name="first_name" id="id_first_name" /></li>
+<li><label for="id_last_name">Last name:</label>
+<input type="text" name="last_name" id="id_last_name" /></li>
+<li><label for="id_birthday">Birthday:</label>
+<input type="text" name="birthday" id="id_birthday" />
+<input type="hidden" name="hidden_text" id="id_hidden_text" /></li>"""
+ )
+ self.assertHTMLEqual(
+ p.as_p(),
+ """<p><label for="id_first_name">First name:</label>
+<input type="text" name="first_name" id="id_first_name" /></p>
+<p><label for="id_last_name">Last name:</label>
+<input type="text" name="last_name" id="id_last_name" /></p>
+<p><label for="id_birthday">Birthday:</label>
+<input type="text" name="birthday" id="id_birthday" />
+<input type="hidden" name="hidden_text" id="id_hidden_text" /></p>"""
+ )
# If a field with a HiddenInput has errors, the as_table() and as_ul() output
# will include the error message(s) with the text "(Hidden field [fieldname]) "
# prepended. This message is displayed at the top of the output, regardless of
# its field's order in the form.
p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
- self.assertHTMLEqual(p.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr>
+ self.assertHTMLEqual(
+ p.as_table(),
+ """<tr><td colspan="2">
+<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr>
<tr><th>First name:</th><td><input type="text" name="first_name" value="John" /></td></tr>
<tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" /></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></td></tr>""")
- self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
+<tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" />
+<input type="hidden" name="hidden_text" /></td></tr>"""
+ )
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
<li>First name: <input type="text" name="first_name" value="John" /></li>
<li>Last name: <input type="text" name="last_name" value="Lennon" /></li>
-<li>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></li>""")
- self.assertHTMLEqual(p.as_p(), """<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul>
+<li>Birthday: <input type="text" name="birthday" value="1940-10-9" />
+<input type="hidden" name="hidden_text" /></li>"""
+ )
+ self.assertHTMLEqual(
+ p.as_p(),
+ """<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul>
<p>First name: <input type="text" name="first_name" value="John" /></p>
<p>Last name: <input type="text" name="last_name" value="Lennon" /></p>
-<p>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></p>""")
+<p>Birthday: <input type="text" name="birthday" value="1940-10-9" /
+><input type="hidden" name="hidden_text" /></p>"""
+ )
# A corner case: It's possible for a form to have only HiddenInputs.
class TestForm(Form):
@@ -1145,7 +1471,8 @@ class FormsTestCase(SimpleTestCase):
address = CharField() # no max_length defined here
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
+ self.assertHTMLEqual(p.as_ul(),
+ """<li>Username: <input type="text" name="username" maxlength="10" /></li>
<li>Password: <input type="password" name="password" maxlength="10" /></li>
<li>Realname: <input type="text" name="realname" maxlength="10" /></li>
<li>Address: <input type="text" name="address" /></li>""")
@@ -1158,7 +1485,8 @@ class FormsTestCase(SimpleTestCase):
password = CharField(max_length=10, widget=PasswordInput)
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
+ self.assertHTMLEqual(p.as_ul(),
+ """<li>Username: <input type="text" name="username" maxlength="10" /></li>
<li>Password: <input type="password" name="password" maxlength="10" /></li>""")
def test_specifying_labels(self):
@@ -1171,7 +1499,8 @@ class FormsTestCase(SimpleTestCase):
password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)')
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Your username: <input type="text" name="username" maxlength="10" /></li>
+ self.assertHTMLEqual(p.as_ul(),
+ """<li>Your username: <input type="text" name="username" maxlength="10" /></li>
<li>Password1: <input type="password" name="password1" /></li>
<li>Contraseña (de nuevo): <input type="password" name="password2" /></li>""")
@@ -1184,16 +1513,22 @@ class FormsTestCase(SimpleTestCase):
q4 = CharField(label='Answer this question!')
q5 = CharField(label='The last question. Period.')
- self.assertHTMLEqual(Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" /></p>
+ self.assertHTMLEqual(
+ Questions(auto_id=False).as_p(),
+ """<p>The first question: <input type="text" name="q1" /></p>
<p>What is your name? <input type="text" name="q2" /></p>
<p>The answer to life is: <input type="text" name="q3" /></p>
<p>Answer this question! <input type="text" name="q4" /></p>
-<p>The last question. Period. <input type="text" name="q5" /></p>""")
- self.assertHTMLEqual(Questions().as_p(), """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" /></p>
+<p>The last question. Period. <input type="text" name="q5" /></p>"""
+ )
+ self.assertHTMLEqual(
+ Questions().as_p(),
+ """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" /></p>
<p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" /></p>
<p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" /></p>
<p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" /></p>
-<p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" /></p>""")
+<p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" /></p>"""
+ )
# If a label is set to the empty string for a field, that field won't get a label.
class UserRegistration(Form):
@@ -1204,8 +1539,11 @@ class FormsTestCase(SimpleTestCase):
self.assertHTMLEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" /></li>
<li>Password: <input type="password" name="password" /></li>""")
p = UserRegistration(auto_id='id_%s')
- self.assertHTMLEqual(p.as_ul(), """<li> <input id="id_username" type="text" name="username" maxlength="10" /></li>
-<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li> <input id="id_username" type="text" name="username" maxlength="10" /></li>
+<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>"""
+ )
# If label is None, Django will auto-create the label from the field name. This
# is default behavior.
@@ -1214,11 +1552,16 @@ class FormsTestCase(SimpleTestCase):
password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
+ self.assertHTMLEqual(p.as_ul(),
+ """<li>Username: <input type="text" name="username" maxlength="10" /></li>
<li>Password: <input type="password" name="password" /></li>""")
p = UserRegistration(auto_id='id_%s')
- self.assertHTMLEqual(p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li>
-<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><label for="id_username">Username:</label>
+<input id="id_username" type="text" name="username" maxlength="10" /></li>
+<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>"""
+ )
def test_label_suffix(self):
# You can specify the 'label_suffix' argument to a Form class to modify the
@@ -1247,7 +1590,12 @@ class FormsTestCase(SimpleTestCase):
<li>Secret answer = <input type="text" name="answer" /></li>""")
f = FavoriteForm(auto_id=False, label_suffix='\u2192')
- self.assertHTMLEqual(f.as_ul(), '<li>Favorite color? <input type="text" name="color" /></li>\n<li>Favorite animal\u2192 <input type="text" name="animal" /></li>\n<li>Secret answer = <input type="text" name="answer" /></li>')
+ self.assertHTMLEqual(
+ f.as_ul(),
+ '<li>Favorite color? <input type="text" name="color" /></li>\n'
+ '<li>Favorite animal\u2192 <input type="text" name="animal" /></li>\n'
+ '<li>Secret answer = <input type="text" name="answer" /></li>'
+ )
def test_initial_data(self):
# You can specify initial data for a field by using the 'initial' argument to a
@@ -1261,19 +1609,36 @@ class FormsTestCase(SimpleTestCase):
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
+<li>Password: <input type="password" name="password" /></li>"""
+ )
# Here, we're submitting data, so the initial value will *not* be displayed.
p = UserRegistration({}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><ul class="errorlist"><li>This field is required.</li></ul>
+Username: <input type="text" name="username" maxlength="10" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Password: <input type="password" name="password" /></li>"""
+ )
p = UserRegistration({'username': ''}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><ul class="errorlist"><li>This field is required.</li></ul>
+Username: <input type="text" name="username" maxlength="10" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Password: <input type="password" name="password" /></li>"""
+ )
p = UserRegistration({'username': 'foo'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Password: <input type="password" name="password" /></li>"""
+ )
# An 'initial' value is *not* used as a fallback if data is not provided. In this
# example, we don't provide a value for 'username', and the form raises a
@@ -1294,22 +1659,41 @@ class FormsTestCase(SimpleTestCase):
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(initial={'username': 'django'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
+<li>Password: <input type="password" name="password" /></li>"""
+ )
p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
+<li>Password: <input type="password" name="password" /></li>"""
+ )
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><ul class="errorlist"><li>This field is required.</li></ul>
+Username: <input type="text" name="username" maxlength="10" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Password: <input type="password" name="password" /></li>"""
+ )
p = UserRegistration({'username': ''}, initial={'username': 'django'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><ul class="errorlist"><li>This field is required.</li></ul>
+Username: <input type="text" name="username" maxlength="10" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Password: <input type="password" name="password" /></li>"""
+ )
p = UserRegistration({'username': 'foo'}, initial={'username': 'django'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Password: <input type="password" name="password" /></li>"""
+ )
# A dynamic 'initial' value is *not* used as a fallback if data is not provided.
# In this example, we don't provide a value for 'username', and the form raises a
@@ -1325,8 +1709,11 @@ class FormsTestCase(SimpleTestCase):
password = CharField(widget=PasswordInput)
p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="babik" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="babik" maxlength="10" /></li>
+<li>Password: <input type="password" name="password" /></li>"""
+ )
def test_callable_initial_data(self):
# The previous technique dealt with raw values as initial data, but it's also
@@ -1351,39 +1738,60 @@ class FormsTestCase(SimpleTestCase):
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
<li>Password: <input type="password" name="password" /></li>
<li>Options: <select multiple="multiple" name="options">
<option value="f" selected="selected">foo</option>
<option value="b" selected="selected">bar</option>
<option value="w">whiz</option>
-</select></li>""")
+</select></li>"""
+ )
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options">
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><ul class="errorlist"><li>This field is required.</li></ul>
+Username: <input type="text" name="username" maxlength="10" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Password: <input type="password" name="password" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Options: <select multiple="multiple" name="options">
<option value="f">foo</option>
<option value="b">bar</option>
<option value="w">whiz</option>
-</select></li>""")
+</select></li>"""
+ )
p = UserRegistration({'username': ''}, initial={'username': initial_django}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options">
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><ul class="errorlist"><li>This field is required.</li></ul>
+ Username: <input type="text" name="username" maxlength="10" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Password: <input type="password" name="password" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Options: <select multiple="multiple" name="options">
<option value="f">foo</option>
<option value="b">bar</option>
<option value="w">whiz</option>
-</select></li>""")
- p = UserRegistration({'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
+</select></li>"""
+ )
+ p = UserRegistration(
+ {'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False
+ )
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>
+Password: <input type="password" name="password" /></li>
<li>Options: <select multiple="multiple" name="options">
<option value="f" selected="selected">foo</option>
<option value="b" selected="selected">bar</option>
<option value="w">whiz</option>
-</select></li>""")
+</select></li>"""
+ )
# A callable 'initial' value is *not* used as a fallback if data is not provided.
# In this example, we don't provide a value for 'username', and the form raises a
@@ -1397,24 +1805,33 @@ class FormsTestCase(SimpleTestCase):
class UserRegistration(Form):
username = CharField(max_length=10, initial=initial_django)
password = CharField(widget=PasswordInput)
- options = MultipleChoiceField(choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')], initial=initial_other_options)
+ options = MultipleChoiceField(
+ choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')],
+ initial=initial_other_options,
+ )
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
<li>Password: <input type="password" name="password" /></li>
<li>Options: <select multiple="multiple" name="options">
<option value="f">foo</option>
<option value="b" selected="selected">bar</option>
<option value="w" selected="selected">whiz</option>
-</select></li>""")
+</select></li>"""
+ )
p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
<li>Password: <input type="password" name="password" /></li>
<li>Options: <select multiple="multiple" name="options">
<option value="f" selected="selected">foo</option>
<option value="b" selected="selected">bar</option>
<option value="w">whiz</option>
-</select></li>""")
+</select></li>"""
+ )
def test_changed_data(self):
class Person(Form):
@@ -1528,17 +1945,37 @@ class FormsTestCase(SimpleTestCase):
password = CharField(widget=PasswordInput, help_text='Wählen Sie mit Bedacht.')
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
-<li>Password: <input type="password" name="password" /> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""")
- self.assertHTMLEqual(p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></p>
-<p>Password: <input type="password" name="password" /> <span class="helptext">Wählen Sie mit Bedacht.</span></p>""")
- self.assertHTMLEqual(p.as_table(), """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /><br /><span class="helptext">e.g., user@example.com</span></td></tr>
-<tr><th>Password:</th><td><input type="password" name="password" /><br /><span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" maxlength="10" />
+<span class="helptext">e.g., user@example.com</span></li>
+<li>Password: <input type="password" name="password" />
+<span class="helptext">Wählen Sie mit Bedacht.</span></li>"""
+ )
+ self.assertHTMLEqual(
+ p.as_p(),
+ """<p>Username: <input type="text" name="username" maxlength="10" />
+<span class="helptext">e.g., user@example.com</span></p>
+<p>Password: <input type="password" name="password" />
+<span class="helptext">Wählen Sie mit Bedacht.</span></p>"""
+ )
+ self.assertHTMLEqual(
+ p.as_table(),
+ """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /><br />
+<span class="helptext">e.g., user@example.com</span></td></tr>
+<tr><th>Password:</th><td><input type="password" name="password" /><br />
+<span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>"""
+ )
# The help text is displayed whether or not data is provided for the form.
p = UserRegistration({'username': 'foo'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" value="foo" maxlength="10" />
+<span class="helptext">e.g., user@example.com</span></li>
+<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" />
+<span class="helptext">Wählen Sie mit Bedacht.</span></li>"""
+ )
# help_text is not displayed for hidden fields. It can be used for documentation
# purposes, though.
@@ -1548,8 +1985,13 @@ class FormsTestCase(SimpleTestCase):
next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
-<li>Password: <input type="password" name="password" /><input type="hidden" name="next" value="/" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>Username: <input type="text" name="username" maxlength="10" />
+<span class="helptext">e.g., user@example.com</span></li>
+<li>Password: <input type="password" name="password" />
+<input type="hidden" name="next" value="/" /></li>"""
+ )
def test_subclassing_forms(self):
# You can subclass a Form to add fields. The resulting form subclass will have
@@ -1564,14 +2006,20 @@ class FormsTestCase(SimpleTestCase):
instrument = CharField()
p = Person(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li>First name: <input type="text" name="first_name" /></li>
<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /></li>""")
+<li>Birthday: <input type="text" name="birthday" /></li>"""
+ )
m = Musician(auto_id=False)
- self.assertHTMLEqual(m.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
+ self.assertHTMLEqual(
+ m.as_ul(),
+ """<li>First name: <input type="text" name="first_name" /></li>
<li>Last name: <input type="text" name="last_name" /></li>
<li>Birthday: <input type="text" name="birthday" /></li>
-<li>Instrument: <input type="text" name="instrument" /></li>""")
+<li>Instrument: <input type="text" name="instrument" /></li>"""
+ )
# Yes, you can subclass multiple forms. The fields are added in the order in
# which the parent classes are listed.
@@ -1612,12 +2060,27 @@ class FormsTestCase(SimpleTestCase):
'person1-birthday': '1940-10-9'
}
p = Person(data, prefix='person1')
- self.assertHTMLEqual(p.as_ul(), """<li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" /></li>
-<li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" /></li>
-<li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /></li>""")
- self.assertHTMLEqual(str(p['first_name']), '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" />')
- self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" />')
- self.assertHTMLEqual(str(p['birthday']), '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" />')
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><label for="id_person1-first_name">First name:</label>
+<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" /></li>
+<li><label for="id_person1-last_name">Last name:</label>
+<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" /></li>
+<li><label for="id_person1-birthday">Birthday:</label>
+<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /></li>"""
+ )
+ self.assertHTMLEqual(
+ str(p['first_name']),
+ '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" />'
+ )
+ self.assertHTMLEqual(
+ str(p['last_name']),
+ '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" />'
+ )
+ self.assertHTMLEqual(
+ str(p['birthday']),
+ '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" />'
+ )
self.assertEqual(p.errors, {})
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data['first_name'], 'John')
@@ -1688,9 +2151,15 @@ class FormsTestCase(SimpleTestCase):
return '%s-prefix-%s' % (self.prefix, field_name) if self.prefix else field_name
p = Person(prefix='foo')
- self.assertHTMLEqual(p.as_ul(), """<li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" /></li>
-<li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" /></li>
-<li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li>""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """<li><label for="id_foo-prefix-first_name">First name:</label>
+<input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" /></li>
+<li><label for="id_foo-prefix-last_name">Last name:</label>
+<input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" /></li>
+<li><label for="id_foo-prefix-birthday">Birthday:</label>
+<input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li>"""
+ )
data = {
'foo-prefix-first_name': 'John',
'foo-prefix-last_name': 'Lennon',
@@ -1768,19 +2237,36 @@ class FormsTestCase(SimpleTestCase):
self.assertHTMLEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
f = FileForm(data={}, files={}, auto_id=False)
- self.assertHTMLEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="file" name="file1" /></td></tr>')
+ self.assertHTMLEqual(
+ f.as_table(),
+ '<tr><th>File1:</th><td>'
+ '<ul class="errorlist"><li>This field is required.</li></ul>'
+ '<input type="file" name="file1" /></td></tr>'
+ )
f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'')}, auto_id=False)
- self.assertHTMLEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>The submitted file is empty.</li></ul><input type="file" name="file1" /></td></tr>')
+ self.assertHTMLEqual(
+ f.as_table(),
+ '<tr><th>File1:</th><td>'
+ '<ul class="errorlist"><li>The submitted file is empty.</li></ul>'
+ '<input type="file" name="file1" /></td></tr>'
+ )
f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False)
- self.assertHTMLEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>No file was submitted. Check the encoding type on the form.</li></ul><input type="file" name="file1" /></td></tr>')
+ self.assertHTMLEqual(
+ f.as_table(),
+ '<tr><th>File1:</th><td>'
+ '<ul class="errorlist"><li>No file was submitted. Check the '
+ 'encoding type on the form.</li></ul>'
+ '<input type="file" name="file1" /></td></tr>'
+ )
f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'some content')}, auto_id=False)
self.assertHTMLEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
self.assertTrue(f.is_valid())
- f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False)
+ file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))
+ f = FileForm(data={}, files={'file1': file1}, auto_id=False)
self.assertHTMLEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
def test_basic_processing_in_view(self):
@@ -1790,7 +2276,8 @@ class FormsTestCase(SimpleTestCase):
password2 = CharField(widget=PasswordInput)
def clean(self):
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2')
+ and self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
return self.cleaned_data
@@ -1804,7 +2291,10 @@ class FormsTestCase(SimpleTestCase):
if form.is_valid():
return 'VALID: %r' % sorted(six.iteritems(form.cleaned_data))
- t = Template('<form action="" method="post">\n<table>\n{{ form }}\n</table>\n<input type="submit" />\n</form>')
+ t = Template(
+ '<form action="" method="post">\n'
+ '<table>\n{{ form }}\n</table>\n<input type="submit" />\n</form>'
+ )
return t.render(Context({'form': form}))
# Case 1: GET (an empty form, with no errors).)
@@ -1817,18 +2307,27 @@ class FormsTestCase(SimpleTestCase):
<input type="submit" />
</form>""")
# Case 2: POST with erroneous data (a redisplayed form, with errors).)
- self.assertHTMLEqual(my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """<form action="" method="post">
+ self.assertHTMLEqual(
+ my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}),
+ """<form action="" method="post">
<table>
<tr><td colspan="2"><ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr>
-<tr><th>Username:</th><td><ul class="errorlist"><li>Ensure this value has at most 10 characters (it has 23).</li></ul><input type="text" name="username" value="this-is-a-long-username" maxlength="10" /></td></tr>
+<tr><th>Username:</th><td><ul class="errorlist">
+<li>Ensure this value has at most 10 characters (it has 23).</li></ul>
+<input type="text" name="username" value="this-is-a-long-username" maxlength="10" /></td></tr>
<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>
</table>
<input type="submit" />
-</form>""")
+</form>"""
+ )
# Case 3: POST with valid data (the success message).)
- self.assertEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}),
- str_prefix("VALID: [('password1', %(_)s'secret'), ('password2', %(_)s'secret'), ('username', %(_)s'adrian')]"))
+ self.assertEqual(
+ my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}),
+ str_prefix(
+ "VALID: [('password1', %(_)s'secret'), ('password2', %(_)s'secret'), ('username', %(_)s'adrian')]"
+ )
+ )
def test_templates_with_forms(self):
class UserRegistration(Form):
@@ -1837,7 +2336,8 @@ class FormsTestCase(SimpleTestCase):
password2 = CharField(widget=PasswordInput)
def clean(self):
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2')
+ and self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
return self.cleaned_data
@@ -1859,12 +2359,17 @@ class FormsTestCase(SimpleTestCase):
<p><label>Password (again): <input type="password" name="password2" /></label></p>
<input type="submit" />
</form>""")
- self.assertHTMLEqual(t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """<form action="">
+ self.assertHTMLEqual(
+ t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})),
+ """<form action="">
<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
-<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password: <input type="password" name="password1" /></label></p>
-<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password (again): <input type="password" name="password2" /></label></p>
+<ul class="errorlist"><li>This field is required.</li></ul><p>
+<label>Password: <input type="password" name="password1" /></label></p>
+<ul class="errorlist"><li>This field is required.</li></ul>
+<p><label>Password (again): <input type="password" name="password2" /></label></p>
<input type="submit" />
-</form>""")
+</form>"""
+ )
# Use form.[field].label to output a field's label. You can specify the label for
# a field by using the 'label' argument to a Field class. If you don't specify
@@ -1914,13 +2419,20 @@ class FormsTestCase(SimpleTestCase):
<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>
<input type="submit" />
</form>''')
- self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
-<p>Username: <input type="text" name="username" maxlength="10" /><br />Good luck picking a username that doesn&#39;t already exist.</p>
+ self.assertHTMLEqual(
+ t.render(Context({'form': UserRegistration(auto_id=False)})),
+ """<form action="">
+<p>Username: <input type="text" name="username" maxlength="10" /><br />
+Good luck picking a username that doesn&#39;t already exist.</p>
<p>Password1: <input type="password" name="password1" /></p>
<p>Password2: <input type="password" name="password2" /></p>
<input type="submit" />
-</form>""")
- self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), '')
+</form>"""
+ )
+ self.assertEqual(
+ Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})),
+ ''
+ )
# To display the errors that aren't associated with a particular field -- e.g.,
# the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the
@@ -1932,12 +2444,17 @@ class FormsTestCase(SimpleTestCase):
{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
<input type="submit" />
</form>''')
- self.assertHTMLEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action="">
+ self.assertHTMLEqual(
+ t.render(Context({
+ 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
+ })),
+ """<form action="">
<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
<p><label>Password: <input type="password" name="password1" /></label></p>
<p><label>Password (again): <input type="password" name="password2" /></label></p>
<input type="submit" />
-</form>""")
+</form>"""
+ )
t = Template('''<form action="">
{{ form.non_field_errors }}
{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
@@ -1945,13 +2462,18 @@ class FormsTestCase(SimpleTestCase):
{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
<input type="submit" />
</form>''')
- self.assertHTMLEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action="">
+ self.assertHTMLEqual(
+ t.render(Context({
+ 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
+ })),
+ """<form action="">
<ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul>
<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
<p><label>Password: <input type="password" name="password1" /></label></p>
<p><label>Password (again): <input type="password" name="password2" /></label></p>
<input type="submit" />
-</form>""")
+</form>"""
+ )
def test_empty_permitted(self):
# Sometimes (pretty much in formsets) we want to allow a form to pass validation
@@ -2013,7 +2535,12 @@ class FormsTestCase(SimpleTestCase):
class MyForm(Form):
field1 = CharField(max_length=50, show_hidden_initial=True)
- self.assertHTMLEqual(MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th><td><input id="id_field1" type="text" name="field1" maxlength="50" /><input type="hidden" name="initial-field1" id="initial-id_field1" /></td></tr>')
+ self.assertHTMLEqual(
+ MyForm().as_table(),
+ '<tr><th><label for="id_field1">Field1:</label></th>'
+ '<td><input id="id_field1" type="text" name="field1" maxlength="50" />'
+ '<input type="hidden" name="initial-field1" id="initial-id_field1" /></td></tr>'
+ )
def test_error_html_required_html_classes(self):
class Person(Form):
@@ -2026,34 +2553,55 @@ class FormsTestCase(SimpleTestCase):
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" /></li>
+ 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" /></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="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" /></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" /></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" /></p>
-<p class="required"><label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool">
+ 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" /></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="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" /></p>""")
+<p class="required error"><label class="required" for="id_age">Age:</label>
+<input type="number" name="age" id="id_age" /></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" /></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">
+ 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" /></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="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" /></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" /></td></tr>"""
+ )
def test_label_has_required_css_class(self):
"""
@@ -2066,8 +2614,10 @@ class FormsTestCase(SimpleTestCase):
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['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):
@@ -2075,7 +2625,11 @@ class FormsTestCase(SimpleTestCase):
happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget)
form = EventForm()
- self.assertHTMLEqual(form.as_ul(), '<input type="hidden" name="happened_at_0" id="id_happened_at_0" /><input type="hidden" name="happened_at_1" id="id_happened_at_1" />')
+ self.assertHTMLEqual(
+ form.as_ul(),
+ '<input type="hidden" name="happened_at_0" id="id_happened_at_0" />'
+ '<input type="hidden" name="happened_at_1" id="id_happened_at_1" />'
+ )
def test_multivalue_field_validation(self):
def bad_names(value):
@@ -2543,17 +3097,26 @@ class FormsTestCase(SimpleTestCase):
p = Person({'first_name': 'John'})
self.assertHTMLEqual(
p.as_ul(),
- """<li><ul class="errorlist nonfield"><li>(Hidden field last_name) This field is required.</li></ul></li><li><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" /><input id="id_last_name" name="last_name" type="hidden" /></li>"""
+ """<li><ul class="errorlist nonfield">
+<li>(Hidden field last_name) This field is required.</li></ul></li><li>
+<label for="id_first_name">First name:</label>
+<input id="id_first_name" name="first_name" type="text" value="John" />
+<input id="id_last_name" name="last_name" type="hidden" /></li>"""
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist nonfield"><li>(Hidden field last_name) This field is required.</li></ul>
-<p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" /><input id="id_last_name" name="last_name" type="hidden" /></p>"""
+<p><label for="id_first_name">First name:</label>
+<input id="id_first_name" name="first_name" type="text" value="John" />
+<input id="id_last_name" name="last_name" type="hidden" /></p>"""
)
self.assertHTMLEqual(
p.as_table(),
- """<tr><td colspan="2"><ul class="errorlist nonfield"><li>(Hidden field last_name) This field is required.</li></ul></td></tr>
-<tr><th><label for="id_first_name">First name:</label></th><td><input id="id_first_name" name="first_name" type="text" value="John" /><input id="id_last_name" name="last_name" type="hidden" /></td></tr>"""
+ """<tr><td colspan="2"><ul class="errorlist nonfield">
+<li>(Hidden field last_name) This field is required.</li></ul></td></tr>
+<tr><th><label for="id_first_name">First name:</label></th><td>
+<input id="id_first_name" name="first_name" type="text" value="John" />
+<input id="id_last_name" name="last_name" type="hidden" /></td></tr>"""
)
def test_error_list_with_non_field_errors_has_correct_class(self):
@@ -2571,8 +3134,12 @@ class FormsTestCase(SimpleTestCase):
)
self.assertHTMLEqual(
p.as_ul(),
- """<li><ul class="errorlist nonfield"><li>Generic validation error</li></ul></li><li><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" /></li>
-<li><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" /></li>"""
+ """<li>
+<ul class="errorlist nonfield"><li>Generic validation error</li></ul></li>
+<li><label for="id_first_name">First name:</label>
+<input id="id_first_name" name="first_name" type="text" value="John" /></li>
+<li><label for="id_last_name">Last name:</label>
+<input id="id_last_name" name="last_name" type="text" value="Lennon" /></li>"""
)
self.assertHTMLEqual(
p.non_field_errors().as_text(),
@@ -2581,14 +3148,18 @@ class FormsTestCase(SimpleTestCase):
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist nonfield"><li>Generic validation error</li></ul>
-<p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" /></p>
-<p><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" /></p>"""
+<p><label for="id_first_name">First name:</label>
+<input id="id_first_name" name="first_name" type="text" value="John" /></p>
+<p><label for="id_last_name">Last name:</label>
+<input id="id_last_name" name="last_name" type="text" value="Lennon" /></p>"""
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><td colspan="2"><ul class="errorlist nonfield"><li>Generic validation error</li></ul></td></tr>
-<tr><th><label for="id_first_name">First name:</label></th><td><input id="id_first_name" name="first_name" type="text" value="John" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><input id="id_last_name" name="last_name" type="text" value="Lennon" /></td></tr>"""
+<tr><th><label for="id_first_name">First name:</label></th><td>
+<input id="id_first_name" name="first_name" type="text" value="John" /></td></tr>
+<tr><th><label for="id_last_name">Last name:</label></th><td>
+<input id="id_last_name" name="last_name" type="text" value="Lennon" /></td></tr>"""
)
def test_errorlist_override(self):
diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py
index 0fea84a782..e3fb1e8005 100644
--- a/tests/forms_tests/tests/test_formsets.py
+++ b/tests/forms_tests/tests/test_formsets.py
@@ -101,9 +101,15 @@ class FormsFormsetTestCase(SimpleTestCase):
# for adding data. By default, it displays 1 blank form. It can display more,
# but we'll look at how to do so later.
formset = self.make_choiceformset()
- self.assertHTMLEqual(str(formset), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="1000" />
+ self.assertHTMLEqual(
+ str(formset),
+ """<input type="hidden" name="choices-TOTAL_FORMS" value="1" />
+<input type="hidden" name="choices-INITIAL_FORMS" value="0" />
+<input type="hidden" name="choices-MIN_NUM_FORMS" value="0" />
+<input type="hidden" name="choices-MAX_NUM_FORMS" value="1000" />
<tr><th>Choice:</th><td><input type="text" name="choices-0-choice" /></td></tr>
-<tr><th>Votes:</th><td><input type="number" name="choices-0-votes" /></td></tr>""")
+<tr><th>Votes:</th><td><input type="number" name="choices-0-votes" /></td></tr>"""
+ )
# We treat FormSet pretty much like we would treat a normal Form. FormSet has an
# is_valid method, and a cleaned_data or errors attribute depending on whether all
@@ -186,10 +192,13 @@ class FormsFormsetTestCase(SimpleTestCase):
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>
+ 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>Choice: <input type="text" name="choices-1-choice" /></li>
-<li>Votes: <input type="number" name="choices-1-votes" /></li>""")
+<li>Votes: <input type="number" name="choices-1-votes" /></li>"""
+ )
# Let's simulate what would happen if we submitted this form.
formset = self.make_choiceformset([('Calexico', '100'), ('', '')], initial_forms=1)
@@ -212,7 +221,10 @@ class FormsFormsetTestCase(SimpleTestCase):
# handle that case later.
formset = self.make_choiceformset([('', ''), ('', '')], initial_forms=1)
self.assertFalse(formset.is_valid())
- self.assertEqual(formset.errors, [{'votes': ['This field is required.'], 'choice': ['This field is required.']}, {}])
+ self.assertEqual(
+ formset.errors,
+ [{'votes': ['This field is required.'], 'choice': ['This field is required.']}, {}]
+ )
def test_displaying_more_than_one_blank_form(self):
# Displaying more than 1 blank form ###########################################
@@ -226,12 +238,15 @@ class FormsFormsetTestCase(SimpleTestCase):
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" /></li>
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<li>Choice: <input type="text" name="choices-0-choice" /></li>
<li>Votes: <input type="number" name="choices-0-votes" /></li>
<li>Choice: <input type="text" name="choices-1-choice" /></li>
<li>Votes: <input type="number" name="choices-1-votes" /></li>
<li>Choice: <input type="text" name="choices-2-choice" /></li>
-<li>Votes: <input type="number" name="choices-2-votes" /></li>""")
+<li>Votes: <input type="number" name="choices-2-votes" /></li>"""
+ )
# Since we displayed every form as blank, we will also accept them back as blank.
# This may seem a little strange, but later we will show how to require a minimum
@@ -269,10 +284,13 @@ class FormsFormsetTestCase(SimpleTestCase):
self.assertFalse(formset.forms[0].empty_permitted)
self.assertTrue(formset.forms[1].empty_permitted)
- self.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" /></li>
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<li>Choice: <input type="text" name="choices-0-choice" /></li>
<li>Votes: <input type="number" name="choices-0-votes" /></li>
<li>Choice: <input type="text" name="choices-1-choice" /></li>
-<li>Votes: <input type="number" name="choices-1-votes" /></li>""")
+<li>Votes: <input type="number" name="choices-1-votes" /></li>"""
+ )
def test_min_num_displaying_more_than_one_blank_form_with_zero_extra(self):
# We can also display more than 1 empty form passing min_num argument
@@ -284,12 +302,15 @@ class FormsFormsetTestCase(SimpleTestCase):
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" /></li>
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<li>Choice: <input type="text" name="choices-0-choice" /></li>
<li>Votes: <input type="number" name="choices-0-votes" /></li>
<li>Choice: <input type="text" name="choices-1-choice" /></li>
<li>Votes: <input type="number" name="choices-1-votes" /></li>
<li>Choice: <input type="text" name="choices-2-choice" /></li>
-<li>Votes: <input type="number" name="choices-2-votes" /></li>""")
+<li>Votes: <input type="number" name="choices-2-votes" /></li>"""
+ )
def test_single_form_completed(self):
# We can just fill out one of the forms.
@@ -388,20 +409,26 @@ class FormsFormsetTestCase(SimpleTestCase):
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>
+ 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>Choice: <input type="text" name="choices-1-choice" /></li>
<li>Votes: <input type="number" name="choices-1-votes" /></li>
<li>Choice: <input type="text" name="choices-2-choice" /></li>
<li>Votes: <input type="number" name="choices-2-votes" /></li>
<li>Choice: <input type="text" name="choices-3-choice" /></li>
-<li>Votes: <input type="number" name="choices-3-votes" /></li>""")
+<li>Votes: <input type="number" name="choices-3-votes" /></li>"""
+ )
# Make sure retrieving an empty form works, and it shows up in the form list
self.assertTrue(formset.empty_form.empty_permitted)
- self.assertHTMLEqual(formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice" /></li>
-<li>Votes: <input type="number" name="choices-__prefix__-votes" /></li>""")
+ self.assertHTMLEqual(
+ formset.empty_form.as_ul(),
+ """<li>Choice: <input type="text" name="choices-__prefix__-choice" /></li>
+<li>Votes: <input type="number" name="choices-__prefix__-votes" /></li>"""
+ )
def test_formset_with_deletion(self):
# FormSets with deletion ######################################################
@@ -418,7 +445,9 @@ class FormsFormsetTestCase(SimpleTestCase):
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>
+ 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>
@@ -426,7 +455,8 @@ class FormsFormsetTestCase(SimpleTestCase):
<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>""")
+<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.
@@ -449,8 +479,18 @@ class FormsFormsetTestCase(SimpleTestCase):
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'}])
+ 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
@@ -517,7 +557,9 @@ class FormsFormsetTestCase(SimpleTestCase):
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>
+ 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>Order: <input type="number" name="choices-0-ORDER" value="1" /></li>
<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li>
@@ -525,7 +567,8 @@ class FormsFormsetTestCase(SimpleTestCase):
<li>Order: <input type="number" name="choices-1-ORDER" value="2" /></li>
<li>Choice: <input type="text" name="choices-2-choice" /></li>
<li>Votes: <input type="number" name="choices-2-votes" /></li>
-<li>Order: <input type="number" name="choices-2-ORDER" /></li>""")
+<li>Order: <input type="number" name="choices-2-ORDER" /></li>"""
+ )
data = {
'choices-TOTAL_FORMS': '3', # the number of forms rendered
@@ -631,7 +674,9 @@ class FormsFormsetTestCase(SimpleTestCase):
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>
+ 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>Order: <input type="number" name="choices-0-ORDER" value="1" /></li>
<li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li>
@@ -646,7 +691,8 @@ class FormsFormsetTestCase(SimpleTestCase):
<li>Choice: <input type="text" name="choices-3-choice" /></li>
<li>Votes: <input type="number" name="choices-3-votes" /></li>
<li>Order: <input type="number" name="choices-3-ORDER" /></li>
-<li>Delete: <input type="checkbox" name="choices-3-DELETE" /></li>""")
+<li>Delete: <input type="checkbox" name="choices-3-DELETE" /></li>"""
+ )
# Let's delete Fergie, and put The Decemberists ahead of Calexico.
@@ -684,7 +730,10 @@ class FormsFormsetTestCase(SimpleTestCase):
{'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': 'The Decemberists'},
{'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': 'Calexico'},
])
- self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': 'Fergie'}])
+ self.assertEqual(
+ [form.cleaned_data for form in formset.deleted_forms],
+ [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': 'Fergie'}]
+ )
def test_invalid_deleted_form_with_ordering(self):
# Should be able to get ordered forms from a valid formset even if a
@@ -761,9 +810,15 @@ class FormsFormsetTestCase(SimpleTestCase):
for form in formset.forms:
form_output.append(str(form))
- self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>
-<tr><th><label for="id_form-2-name">Name:</label></th><td><input type="text" name="form-2-name" id="id_form-2-name" /></td></tr>""")
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<tr><th><label for="id_form-0-name">Name:</label></th>
+<td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>
+<tr><th><label for="id_form-1-name">Name:</label></th>
+<td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>
+<tr><th><label for="id_form-2-name">Name:</label></th>
+<td><input type="text" name="form-2-name" id="id_form-2-name" /></td></tr>"""
+ )
# If max_num is 0 then no form is rendered at all.
LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0)
@@ -782,8 +837,13 @@ class FormsFormsetTestCase(SimpleTestCase):
for form in formset.forms:
form_output.append(str(form))
- self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""")
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<tr><th><label for="id_form-0-name">Name:</label></th><td>
+<input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>
+<tr><th><label for="id_form-1-name">Name:</label></th>
+<td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>"""
+ )
# Ensure that max_num has no effect when extra is less than max_num.
@@ -794,7 +854,11 @@ class FormsFormsetTestCase(SimpleTestCase):
for form in formset.forms:
form_output.append(str(form))
- self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>""")
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<tr><th><label for="id_form-0-name">Name:</label></th>
+<td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>"""
+ )
def test_max_num_with_initial_data(self):
# max_num with initial data
@@ -813,8 +877,13 @@ class FormsFormsetTestCase(SimpleTestCase):
for form in formset.forms:
form_output.append(str(form))
- self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name" /></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""")
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<tr><th><label for="id_form-0-name">Name:</label></th>
+<td><input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name" /></td></tr>
+<tr><th><label for="id_form-1-name">Name:</label></th>
+<td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>"""
+ )
def test_max_num_zero(self):
# If max_num is 0 then no form is rendered at all, regardless of extra,
@@ -842,8 +911,13 @@ class FormsFormsetTestCase(SimpleTestCase):
for form in formset.forms:
form_output.append(str(form))
- self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke" /></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary" /></td></tr>""")
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<tr><th><label for="id_form-0-name">Name:</label></th>
+<td><input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke" /></td></tr>
+<tr><th><label for="id_form-1-name">Name:</label></th>
+<td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary" /></td></tr>"""
+ )
def test_more_initial_than_max_num(self):
# More initial forms than max_num now results in all initial forms
@@ -861,9 +935,15 @@ class FormsFormsetTestCase(SimpleTestCase):
for form in formset.forms:
form_output.append(str(form))
- self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic" /></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary" /></td></tr>
-<tr><th><label for="id_form-2-name">Name:</label></th><td><input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke" /></td></tr>""")
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<tr><th><label for="id_form-0-name">Name:</label></th>
+<td><input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic" /></td></tr>
+<tr><th><label for="id_form-1-name">Name:</label></th>
+<td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary" /></td></tr>
+<tr><th><label for="id_form-2-name">Name:</label></th>
+<td><input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke" /></td></tr>"""
+ )
# One form from initial and extra=3 with max_num=2 should result in the one
# initial form and one extra.
@@ -877,8 +957,13 @@ class FormsFormsetTestCase(SimpleTestCase):
for form in formset.forms:
form_output.append(str(form))
- self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""")
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """<tr><th><label for="id_form-0-name">Name:</label></th>
+<td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr>
+<tr><th><label for="id_form-1-name">Name:</label></th>
+<td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>"""
+ )
def test_regression_6926(self):
# Regression test for #6926 ##################################################
@@ -1157,21 +1242,39 @@ ChoiceFormSet = formset_factory(Choice)
class FormsetAsFooTests(SimpleTestCase):
def test_as_table(self):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
- self.assertHTMLEqual(formset.as_table(), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" />
+ self.assertHTMLEqual(
+ formset.as_table(),
+ """<input type="hidden" name="choices-TOTAL_FORMS" value="1" />
+<input type="hidden" name="choices-INITIAL_FORMS" value="0" />
+<input type="hidden" name="choices-MIN_NUM_FORMS" value="0" />
+<input type="hidden" name="choices-MAX_NUM_FORMS" value="0" />
<tr><th>Choice:</th><td><input type="text" name="choices-0-choice" value="Calexico" /></td></tr>
-<tr><th>Votes:</th><td><input type="number" name="choices-0-votes" value="100" /></td></tr>""")
+<tr><th>Votes:</th><td><input type="number" name="choices-0-votes" value="100" /></td></tr>"""
+ )
def test_as_p(self):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
- self.assertHTMLEqual(formset.as_p(), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" />
+ self.assertHTMLEqual(
+ formset.as_p(),
+ """<input type="hidden" name="choices-TOTAL_FORMS" value="1" />
+<input type="hidden" name="choices-INITIAL_FORMS" value="0" />
+<input type="hidden" name="choices-MIN_NUM_FORMS" value="0" />
+<input type="hidden" name="choices-MAX_NUM_FORMS" value="0" />
<p>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></p>
-<p>Votes: <input type="number" name="choices-0-votes" value="100" /></p>""")
+<p>Votes: <input type="number" name="choices-0-votes" value="100" /></p>"""
+ )
def test_as_ul(self):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
- self.assertHTMLEqual(formset.as_ul(), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" />
+ self.assertHTMLEqual(
+ formset.as_ul(),
+ """<input type="hidden" name="choices-TOTAL_FORMS" value="1" />
+<input type="hidden" name="choices-INITIAL_FORMS" value="0" />
+<input type="hidden" name="choices-MIN_NUM_FORMS" value="0" />
+<input type="hidden" name="choices-MAX_NUM_FORMS" value="0" />
<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>Votes: <input type="number" name="choices-0-votes" value="100" /></li>"""
+ )
# Regression test for #11418 #################################################
@@ -1241,8 +1344,14 @@ class TestEmptyFormSet(SimpleTestCase):
def test_empty_formset_is_valid(self):
"""Test that an empty formset still calls clean()"""
EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate)
- formset = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '0'}, prefix="form")
- formset2 = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '1', 'form-0-name': 'bah'}, prefix="form")
+ formset = EmptyFsetWontValidateFormset(
+ data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '0'},
+ prefix="form",
+ )
+ formset2 = EmptyFsetWontValidateFormset(
+ data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '1', 'form-0-name': 'bah'},
+ prefix="form",
+ )
self.assertFalse(formset.is_valid())
self.assertFalse(formset2.is_valid())
diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py
index 4ec5f6ab7e..f48983779c 100644
--- a/tests/forms_tests/tests/test_media.py
+++ b/tests/forms_tests/tests/test_media.py
@@ -14,12 +14,18 @@ class FormsMediaTestCase(SimpleTestCase):
def test_construction(self):
# Check construction of media objects
- m = Media(css={'all': ('path/to/css1', '/path/to/css2')}, js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'))
- self.assertEqual(str(m), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ m = Media(
+ css={'all': ('path/to/css1', '/path/to/css2')},
+ js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'),
+ )
+ self.assertEqual(
+ str(m),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
class Foo:
css = {
@@ -28,11 +34,14 @@ class FormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
m3 = Media(Foo)
- self.assertEqual(str(m3), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(m3),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
# A widget can exist without a media definition
class MyWidget(TextInput):
@@ -57,19 +66,27 @@ class FormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
w1 = MyWidget1()
- self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w1.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
# Media objects can be interrogated by media type
- self.assertEqual(str(w1.media['css']), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w1.media['css']),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />""")
- self.assertEqual(str(w1.media['js']), """<script type="text/javascript" src="/path/to/js1"></script>
+ self.assertEqual(
+ str(w1.media['js']),
+ """<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
def test_combine_media(self):
# Media objects can be combined. Any given media resource will appear only
@@ -98,20 +115,26 @@ class FormsMediaTestCase(SimpleTestCase):
w1 = MyWidget1()
w2 = MyWidget2()
w3 = MyWidget3()
- self.assertEqual(str(w1.media + w2.media + w3.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w1.media + w2.media + w3.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
# Check that media addition hasn't affected the original objects
- self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w1.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
# Regression check for #12879: specifying the same CSS or JS file
# multiple times in a single Media instance should result in that file
@@ -122,8 +145,11 @@ class FormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', '/path/to/js1')
w4 = MyWidget4()
- self.assertEqual(str(w4.media), """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet" />
-<script type="text/javascript" src="/path/to/js1"></script>""")
+ self.assertEqual(
+ str(w4.media),
+ """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+<script type="text/javascript" src="/path/to/js1"></script>"""
+ )
def test_media_property(self):
###############################################################
@@ -147,10 +173,13 @@ class FormsMediaTestCase(SimpleTestCase):
media = property(_media)
w5 = MyWidget5()
- self.assertEqual(str(w5.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w5.media),
+ """<link href="/some/path" type="text/css" media="all" rel="stylesheet" />
<link href="/other/path" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/some/js"></script>
-<script type="text/javascript" src="/other/js"></script>""")
+<script type="text/javascript" src="/other/js"></script>"""
+ )
def test_media_property_parent_references(self):
# Media properties can reference the media of their parents,
@@ -168,13 +197,16 @@ class FormsMediaTestCase(SimpleTestCase):
media = property(_media)
w6 = MyWidget6()
- self.assertEqual(str(w6.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w6.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/other/path" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/other/js"></script>""")
+<script type="text/javascript" src="/other/js"></script>"""
+ )
def test_media_inheritance(self):
###############################################################
@@ -193,11 +225,14 @@ class FormsMediaTestCase(SimpleTestCase):
pass
w7 = MyWidget7()
- self.assertEqual(str(w7.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w7.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
# If a widget extends another but defines media, it extends the parent widget's media by default
class MyWidget8(MyWidget1):
@@ -208,13 +243,16 @@ class FormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', '/path/to/js4')
w8 = MyWidget8()
- self.assertEqual(str(w8.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w8.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_media_inheritance_from_property(self):
# If a widget extends another but defines media, it extends the parents widget's media,
@@ -239,10 +277,13 @@ class FormsMediaTestCase(SimpleTestCase):
js = ('/other/js',)
w9 = MyWidget9()
- self.assertEqual(str(w9.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w9.media),
+ """<link href="/some/path" type="text/css" media="all" rel="stylesheet" />
<link href="/other/path" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/some/js"></script>
-<script type="text/javascript" src="/other/js"></script>""")
+<script type="text/javascript" src="/other/js"></script>"""
+ )
# A widget can disable media inheritance by specifying 'extend=False'
class MyWidget10(MyWidget1):
@@ -277,13 +318,16 @@ class FormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', '/path/to/js4')
w11 = MyWidget11()
- self.assertEqual(str(w11.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w11.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_media_inheritance_single_type(self):
# A widget can enable inheritance of one media type by specifying extend as a tuple
@@ -303,11 +347,14 @@ class FormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', '/path/to/js4')
w12 = MyWidget12()
- self.assertEqual(str(w12.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w12.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_multi_media(self):
###############################################################
@@ -325,12 +372,15 @@ class FormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', '/path/to/js4')
multimedia = MultimediaWidget()
- self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" />
+ self.assertEqual(
+ str(multimedia.media),
+ """<link href="/file4" type="text/css" media="print" rel="stylesheet" />
<link href="/file3" type="text/css" media="screen" rel="stylesheet" />
<link href="/file1" type="text/css" media="screen, print" rel="stylesheet" />
<link href="/file2" type="text/css" media="screen, print" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_multi_widget(self):
###############################################################
@@ -366,13 +416,16 @@ class FormsMediaTestCase(SimpleTestCase):
super(MyMultiWidget, self).__init__(widgets, attrs)
mymulti = MyMultiWidget()
- self.assertEqual(str(mymulti.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(mymulti.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_form_media(self):
###############################################################
@@ -405,25 +458,31 @@ class FormsMediaTestCase(SimpleTestCase):
field1 = CharField(max_length=20, widget=MyWidget1())
field2 = CharField(max_length=20, widget=MyWidget2())
f1 = MyForm()
- self.assertEqual(str(f1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(f1.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
# Form media can be combined to produce a single media definition.
class AnotherForm(Form):
field3 = CharField(max_length=20, widget=MyWidget3())
f2 = AnotherForm()
- self.assertEqual(str(f1.media + f2.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(f1.media + f2.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
# Forms can also define media, following the same rules as widgets.
class FormWithMedia(Form):
@@ -436,7 +495,9 @@ class FormsMediaTestCase(SimpleTestCase):
'all': ('/some/form/css',)
}
f3 = FormWithMedia()
- self.assertEqual(str(f3.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(f3.media),
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />
@@ -444,17 +505,23 @@ class FormsMediaTestCase(SimpleTestCase):
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
<script type="text/javascript" src="/path/to/js4"></script>
-<script type="text/javascript" src="/some/form/javascript"></script>""")
+<script type="text/javascript" src="/some/form/javascript"></script>"""
+ )
# Media works in templates
- self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """<script type="text/javascript" src="/path/to/js1"></script>
+ self.assertEqual(
+ Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})),
+ """<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
<script type="text/javascript" src="/path/to/js4"></script>
-<script type="text/javascript" src="/some/form/javascript"></script><link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+<script type="text/javascript" src="/some/form/javascript"></script>"""
+ """<link href="http://media.example.com/media/path/to/css1" type="text/css" """
+ """media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
-<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""")
+<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />"""
+ )
def test_html_safe(self):
media = Media(css={'all': ['/path/to/css']}, js=['/path/to/js'])
@@ -471,12 +538,18 @@ class StaticFormsMediaTestCase(SimpleTestCase):
def test_construction(self):
# Check construction of media objects
- m = Media(css={'all': ('path/to/css1', '/path/to/css2')}, js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'))
- self.assertEqual(str(m), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ m = Media(
+ css={'all': ('path/to/css1', '/path/to/css2')},
+ js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'),
+ )
+ self.assertEqual(
+ str(m),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
class Foo:
css = {
@@ -485,11 +558,14 @@ class StaticFormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
m3 = Media(Foo)
- self.assertEqual(str(m3), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(m3),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
# A widget can exist without a media definition
class MyWidget(TextInput):
@@ -514,19 +590,28 @@ class StaticFormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
w1 = MyWidget1()
- self.assertEqual(str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w1.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
# Media objects can be interrogated by media type
- self.assertEqual(str(w1.media['css']), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />""")
+ self.assertEqual(
+ str(w1.media['css']),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />"""
+ )
- self.assertEqual(str(w1.media['js']), """<script type="text/javascript" src="/path/to/js1"></script>
+ self.assertEqual(
+ str(w1.media['js']),
+ """<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
def test_combine_media(self):
# Media objects can be combined. Any given media resource will appear only
@@ -555,20 +640,26 @@ class StaticFormsMediaTestCase(SimpleTestCase):
w1 = MyWidget1()
w2 = MyWidget2()
w3 = MyWidget3()
- self.assertEqual(str(w1.media + w2.media + w3.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w1.media + w2.media + w3.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
# Check that media addition hasn't affected the original objects
- self.assertEqual(str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w1.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
# Regression check for #12879: specifying the same CSS or JS file
# multiple times in a single Media instance should result in that file
@@ -625,13 +716,16 @@ class StaticFormsMediaTestCase(SimpleTestCase):
media = property(_media)
w6 = MyWidget6()
- self.assertEqual(str(w6.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w6.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/other/path" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/other/js"></script>""")
+<script type="text/javascript" src="/other/js"></script>"""
+ )
def test_media_inheritance(self):
###############################################################
@@ -650,11 +744,14 @@ class StaticFormsMediaTestCase(SimpleTestCase):
pass
w7 = MyWidget7()
- self.assertEqual(str(w7.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w7.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
-<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""")
+<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
+ )
# If a widget extends another but defines media, it extends the parent widget's media by default
class MyWidget8(MyWidget1):
@@ -665,13 +762,16 @@ class StaticFormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', '/path/to/js4')
w8 = MyWidget8()
- self.assertEqual(str(w8.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w8.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_media_inheritance_from_property(self):
# If a widget extends another but defines media, it extends the parents widget's media,
@@ -696,10 +796,13 @@ class StaticFormsMediaTestCase(SimpleTestCase):
js = ('/other/js',)
w9 = MyWidget9()
- self.assertEqual(str(w9.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w9.media),
+ """<link href="/some/path" type="text/css" media="all" rel="stylesheet" />
<link href="/other/path" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/some/js"></script>
-<script type="text/javascript" src="/other/js"></script>""")
+<script type="text/javascript" src="/other/js"></script>"""
+ )
# A widget can disable media inheritance by specifying 'extend=False'
class MyWidget10(MyWidget1):
@@ -734,13 +837,16 @@ class StaticFormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', '/path/to/js4')
w11 = MyWidget11()
- self.assertEqual(str(w11.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w11.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_media_inheritance_single_type(self):
# A widget can enable inheritance of one media type by specifying extend as a tuple
@@ -760,11 +866,14 @@ class StaticFormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', '/path/to/js4')
w12 = MyWidget12()
- self.assertEqual(str(w12.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(w12.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_multi_media(self):
###############################################################
@@ -782,12 +891,15 @@ class StaticFormsMediaTestCase(SimpleTestCase):
js = ('/path/to/js1', '/path/to/js4')
multimedia = MultimediaWidget()
- self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" />
+ self.assertEqual(
+ str(multimedia.media),
+ """<link href="/file4" type="text/css" media="print" rel="stylesheet" />
<link href="/file3" type="text/css" media="screen" rel="stylesheet" />
<link href="/file1" type="text/css" media="screen, print" rel="stylesheet" />
<link href="/file2" type="text/css" media="screen, print" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_multi_widget(self):
###############################################################
@@ -823,13 +935,16 @@ class StaticFormsMediaTestCase(SimpleTestCase):
super(MyMultiWidget, self).__init__(widgets, attrs)
mymulti = MyMultiWidget()
- self.assertEqual(str(mymulti.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(mymulti.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
def test_form_media(self):
###############################################################
@@ -862,25 +977,31 @@ class StaticFormsMediaTestCase(SimpleTestCase):
field1 = CharField(max_length=20, widget=MyWidget1())
field2 = CharField(max_length=20, widget=MyWidget2())
f1 = MyForm()
- self.assertEqual(str(f1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(f1.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
# Form media can be combined to produce a single media definition.
class AnotherForm(Form):
field3 = CharField(max_length=20, widget=MyWidget3())
f2 = AnotherForm()
- self.assertEqual(str(f1.media + f2.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(f1.media + f2.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
-<script type="text/javascript" src="/path/to/js4"></script>""")
+<script type="text/javascript" src="/path/to/js4"></script>"""
+ )
# Forms can also define media, following the same rules as widgets.
class FormWithMedia(Form):
@@ -893,7 +1014,9 @@ class StaticFormsMediaTestCase(SimpleTestCase):
'all': ('/some/form/css',)
}
f3 = FormWithMedia()
- self.assertEqual(str(f3.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+ self.assertEqual(
+ str(f3.media),
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />
@@ -901,14 +1024,19 @@ class StaticFormsMediaTestCase(SimpleTestCase):
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
<script type="text/javascript" src="/path/to/js4"></script>
-<script type="text/javascript" src="/some/form/javascript"></script>""")
+<script type="text/javascript" src="/some/form/javascript"></script>"""
+ )
# Media works in templates
- self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """<script type="text/javascript" src="/path/to/js1"></script>
+ self.assertEqual(
+ Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})),
+ """<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>
<script type="text/javascript" src="/path/to/js4"></script>
-<script type="text/javascript" src="/some/form/javascript"></script><link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
+<script type="text/javascript" src="/some/form/javascript"></script>"""
+ """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
-<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""")
+<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />"""
+ )
diff --git a/tests/forms_tests/tests/test_regressions.py b/tests/forms_tests/tests/test_regressions.py
index d2f86e1db9..10e5b3f983 100644
--- a/tests/forms_tests/tests/test_regressions.py
+++ b/tests/forms_tests/tests/test_regressions.py
@@ -22,7 +22,11 @@ class FormsRegressionsTestCase(TestCase):
f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs))
f2 = CharField(widget=TextInput(attrs=extra_attrs))
- self.assertHTMLEqual(TestForm(auto_id=False).as_p(), '<p>F1: <input type="text" class="special" name="f1" maxlength="10" /></p>\n<p>F2: <input type="text" class="special" name="f2" /></p>')
+ self.assertHTMLEqual(
+ TestForm(auto_id=False).as_p(),
+ '<p>F1: <input type="text" class="special" name="f1" maxlength="10" /></p>\n'
+ '<p>F2: <input type="text" class="special" name="f2" /></p>'
+ )
def test_regression_3600(self):
# Tests for form i18n #
@@ -32,19 +36,35 @@ class FormsRegressionsTestCase(TestCase):
username = CharField(max_length=10, label=ugettext_lazy('username'))
f = SomeForm()
- self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
+ self.assertHTMLEqual(
+ f.as_p(),
+ '<p><label for="id_username">username:</label>'
+ '<input id="id_username" type="text" name="username" maxlength="10" /></p>'
+ )
# Translations are done at rendering time, so multi-lingual apps can define forms)
with translation.override('de'):
- self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
+ self.assertHTMLEqual(
+ f.as_p(),
+ '<p><label for="id_username">Benutzername:</label>'
+ '<input id="id_username" type="text" name="username" maxlength="10" /></p>'
+ )
with translation.override('pl'):
- self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">u\u017cytkownik:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
+ self.assertHTMLEqual(
+ f.as_p(),
+ '<p><label for="id_username">u\u017cytkownik:</label>'
+ '<input id="id_username" type="text" name="username" maxlength="10" /></p>'
+ )
def test_regression_5216(self):
# There was some problems with form translations in #5216
class SomeForm(Form):
field_1 = CharField(max_length=10, label=ugettext_lazy('field_1'))
- field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'}))
+ field_2 = CharField(
+ max_length=10,
+ label=ugettext_lazy('field_2'),
+ widget=TextInput(attrs={'id': 'field_2_id'}),
+ )
f = SomeForm()
self.assertHTMLEqual(f['field_1'].label_tag(), '<label for="id_field_1">field_1:</label>')
@@ -57,12 +77,38 @@ class FormsRegressionsTestCase(TestCase):
somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label='\xc5\xf8\xdf')
f = SomeForm()
- self.assertHTMLEqual(f.as_p(), '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul id="id_somechoice">\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>')
+ self.assertHTMLEqual(
+ f.as_p(),
+ '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label>'
+ '<ul id="id_somechoice">\n'
+ '<li><label for="id_somechoice_0">'
+ '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> '
+ 'En tied\xe4</label></li>\n'
+ '<li><label for="id_somechoice_1">'
+ '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> '
+ 'Mies</label></li>\n<li><label for="id_somechoice_2">'
+ '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> '
+ 'Nainen</label></li>\n</ul></p>'
+ )
# Translated error messages used to be buggy.
with translation.override('ru'):
f = SomeForm({})
- self.assertHTMLEqual(f.as_p(), '<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul id="id_somechoice">\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>')
+ self.assertHTMLEqual(
+ f.as_p(),
+ '<ul class="errorlist"><li>'
+ '\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c'
+ '\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n'
+ '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label>'
+ ' <ul id="id_somechoice">\n<li><label for="id_somechoice_0">'
+ '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> '
+ 'En tied\xe4</label></li>\n'
+ '<li><label for="id_somechoice_1">'
+ '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> '
+ 'Mies</label></li>\n<li><label for="id_somechoice_2">'
+ '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> '
+ 'Nainen</label></li>\n</ul></p>'
+ )
# Deep copying translated text shouldn't raise an error)
class CopyForm(Form):
@@ -95,8 +141,18 @@ class FormsRegressionsTestCase(TestCase):
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>')
+ 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_xss_error_messages(self):
###################################################
@@ -114,13 +170,23 @@ class FormsRegressionsTestCase(TestCase):
field = ChoiceField(choices=[('one', 'One')])
f = SomeForm({'field': '<script>'})
- self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')
+ self.assertHTMLEqual(
+ t.render(Context({'form': f})),
+ '<ul class="errorlist"><li>field<ul class="errorlist">'
+ '<li>Select a valid choice. &lt;script&gt; is not one of the '
+ 'available choices.</li></ul></li></ul>'
+ )
class SomeForm(Form):
field = MultipleChoiceField(choices=[('one', 'One')])
f = SomeForm({'field': ['<script>']})
- self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')
+ self.assertHTMLEqual(
+ t.render(Context({'form': f})),
+ '<ul class="errorlist"><li>field<ul class="errorlist">'
+ '<li>Select a valid choice. &lt;script&gt; is not one of the '
+ 'available choices.</li></ul></li></ul>'
+ )
from forms_tests.models import ChoiceModel
@@ -128,7 +194,12 @@ class FormsRegressionsTestCase(TestCase):
field = ModelMultipleChoiceField(ChoiceModel.objects.all())
f = SomeForm({'field': ['<script>']})
- self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>&quot;&lt;script&gt;&quot; is not a valid value for a primary key.</li></ul></li></ul>')
+ self.assertHTMLEqual(
+ t.render(Context({'form': f})),
+ '<ul class="errorlist"><li>field<ul class="errorlist">'
+ '<li>&quot;&lt;script&gt;&quot; is not a valid value for a '
+ 'primary key.</li></ul></li></ul>'
+ )
def test_regression_14234(self):
"""
diff --git a/tests/forms_tests/tests/test_utils.py b/tests/forms_tests/tests/test_utils.py
index d13c59ed79..260306165f 100644
--- a/tests/forms_tests/tests/test_utils.py
+++ b/tests/forms_tests/tests/test_utils.py
@@ -22,9 +22,18 @@ class FormsUtilsTestCase(SimpleTestCase):
self.assertEqual(flatatt({'id': "header"}), ' id="header"')
self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"')
- self.assertEqual(flatatt({'class': "news", 'title': "Read this", 'required': "required"}), ' class="news" required="required" title="Read this"')
- self.assertEqual(flatatt({'class': "news", 'title': "Read this", 'required': True}), ' class="news" title="Read this" required')
- self.assertEqual(flatatt({'class': "news", 'title': "Read this", 'required': False}), ' class="news" title="Read this"')
+ self.assertEqual(
+ flatatt({'class': "news", 'title': "Read this", 'required': "required"}),
+ ' class="news" required="required" title="Read this"'
+ )
+ self.assertEqual(
+ flatatt({'class': "news", 'title': "Read this", 'required': True}),
+ ' class="news" title="Read this" required'
+ )
+ self.assertEqual(
+ flatatt({'class': "news", 'title': "Read this", 'required': False}),
+ ' class="news" title="Read this"'
+ )
self.assertEqual(flatatt({}), '')
def test_flatatt_no_side_effects(self):
@@ -97,19 +106,33 @@ class FormsUtilsTestCase(SimpleTestCase):
return "A very bad error."
# Can take a non-string.
- self.assertHTMLEqual(str(ErrorList(ValidationError(VeryBadError()).messages)),
- '<ul class="errorlist"><li>A very bad error.</li></ul>')
+ self.assertHTMLEqual(
+ str(ErrorList(ValidationError(VeryBadError()).messages)),
+ '<ul class="errorlist"><li>A very bad error.</li></ul>'
+ )
# Escapes non-safe input but not input marked safe.
example = 'Example of link: <a href="http://www.example.com/">example</a>'
- self.assertHTMLEqual(str(ErrorList([example])),
- '<ul class="errorlist"><li>Example of link: &lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>')
- self.assertHTMLEqual(str(ErrorList([mark_safe(example)])),
- '<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul>')
- self.assertHTMLEqual(str(ErrorDict({'name': example})),
- '<ul class="errorlist"><li>nameExample of link: &lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>')
- self.assertHTMLEqual(str(ErrorDict({'name': mark_safe(example)})),
- '<ul class="errorlist"><li>nameExample of link: <a href="http://www.example.com/">example</a></li></ul>')
+ self.assertHTMLEqual(
+ str(ErrorList([example])),
+ '<ul class="errorlist"><li>Example of link: '
+ '&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>'
+ )
+ self.assertHTMLEqual(
+ str(ErrorList([mark_safe(example)])),
+ '<ul class="errorlist"><li>Example of link: '
+ '<a href="http://www.example.com/">example</a></li></ul>'
+ )
+ self.assertHTMLEqual(
+ str(ErrorDict({'name': example})),
+ '<ul class="errorlist"><li>nameExample of link: '
+ '&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>'
+ )
+ self.assertHTMLEqual(
+ str(ErrorDict({'name': mark_safe(example)})),
+ '<ul class="errorlist"><li>nameExample of link: '
+ '<a href="http://www.example.com/">example</a></li></ul>'
+ )
def test_error_dict_copy(self):
e = ErrorDict()
diff --git a/tests/forms_tests/tests/test_validators.py b/tests/forms_tests/tests/test_validators.py
index 2f42d2ad44..cb7104756a 100644
--- a/tests/forms_tests/tests/test_validators.py
+++ b/tests/forms_tests/tests/test_validators.py
@@ -40,7 +40,11 @@ class UserForm(forms.Form):
class TestFieldWithValidators(TestCase):
def test_all_errors_get_reported(self):
- form = UserForm({'full_name': 'not int nor mail', 'string': '2 is not correct', 'ignore_case_string': "IgnORE Case strIng"})
+ form = UserForm({
+ 'full_name': 'not int nor mail',
+ 'string': '2 is not correct',
+ 'ignore_case_string': "IgnORE Case strIng",
+ })
self.assertRaises(ValidationError, form.fields['full_name'].clean, 'not int nor mail')
try:
diff --git a/tests/forms_tests/tests/test_widgets.py b/tests/forms_tests/tests/test_widgets.py
index d1010fe174..114f824eb9 100644
--- a/tests/forms_tests/tests/test_widgets.py
+++ b/tests/forms_tests/tests/test_widgets.py
@@ -34,7 +34,15 @@ class FormsWidgetTests(SimpleTestCase):
inp_set1.append(str(inp))
inp_set2.append('%s<br />' % inp)
inp_set3.append('<p>%s %s</p>' % (inp.tag(), inp.choice_label))
- inp_set4.append('%s %s %s %s %s' % (inp.name, inp.value, inp.choice_value, inp.choice_label, inp.is_checked()))
+ inp_set4.append(
+ '%s %s %s %s %s' % (
+ inp.name,
+ inp.value,
+ inp.choice_value,
+ inp.choice_label,
+ inp.is_checked(),
+ )
+ )
self.assertHTMLEqual('\n'.join(inp_set1), """<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label>
<label><input type="radio" name="beatle" value="P" /> Paul</label>
@@ -57,7 +65,10 @@ beatle J R Ringo False""")
w = RadioSelect()
r = w.get_renderer('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
self.assertHTMLEqual(str(r[1]), '<label><input type="radio" name="beatle" value="P" /> Paul</label>')
- self.assertHTMLEqual(str(r[0]), '<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label>')
+ self.assertHTMLEqual(
+ str(r[0]),
+ '<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label>'
+ )
self.assertTrue(r[0].is_checked())
self.assertFalse(r[1].is_checked())
self.assertEqual((r[1].name, r[1].value, r[1].choice_value, r[1].choice_label), ('beatle', 'J', 'P', 'Paul'))
@@ -76,30 +87,39 @@ beatle J R Ringo False""")
def render(self):
return '<br />\n'.join(six.text_type(choice) for choice in self)
w = RadioSelect(renderer=MyRenderer)
- self.assertHTMLEqual(w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<label><input type="radio" name="beatle" value="J" /> John</label><br />
+ self.assertHTMLEqual(
+ w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))),
+ """<label><input type="radio" name="beatle" value="J" /> John</label><br />
<label><input type="radio" name="beatle" value="P" /> Paul</label><br />
<label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br />
-<label><input type="radio" name="beatle" value="R" /> Ringo</label>""")
+<label><input type="radio" name="beatle" value="R" /> Ringo</label>"""
+ )
# Or you can use custom RadioSelect fields that use your custom renderer.
class CustomRadioSelect(RadioSelect):
renderer = MyRenderer
w = CustomRadioSelect()
- self.assertHTMLEqual(w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<label><input type="radio" name="beatle" value="J" /> John</label><br />
+ self.assertHTMLEqual(
+ w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))),
+ """<label><input type="radio" name="beatle" value="J" /> John</label><br />
<label><input type="radio" name="beatle" value="P" /> Paul</label><br />
<label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br />
-<label><input type="radio" name="beatle" value="R" /> Ringo</label>""")
+<label><input type="radio" name="beatle" value="R" /> Ringo</label>"""
+ )
# You can customize rendering with outer_html/inner_html renderer variables (#22950)
class MyRenderer(RadioFieldRenderer):
- outer_html = str('<div{id_attr}>{content}</div>') # str is just to test some Python 2 issue with bytestrings
+ # str is just to test some Python 2 issue with bytestrings
+ outer_html = str('<div{id_attr}>{content}</div>')
inner_html = '<p>{choice_value}{sub_widgets}</p>'
w = RadioSelect(renderer=MyRenderer)
output = w.render('beatle', 'J',
choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')),
attrs={'id': 'bar'})
self.assertIsInstance(output, SafeData)
- self.assertHTMLEqual(output, """<div id="bar">
+ self.assertHTMLEqual(
+ output,
+ """<div id="bar">
<p><label for="bar_0"><input checked="checked" type="radio" id="bar_0" value="J" name="beatle" /> John</label></p>
<p><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle" /> Paul</label></p>
<p><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle" /> George</label></p>
diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py
index b81053c6cb..a633b2da8a 100644
--- a/tests/forms_tests/tests/tests.py
+++ b/tests/forms_tests/tests/tests.py
@@ -101,7 +101,9 @@ class ModelFormCallableModelDefault(TestCase):
ChoiceOptionModel.objects.create(id=1, name='default')
ChoiceOptionModel.objects.create(id=2, name='option 2')
ChoiceOptionModel.objects.create(id=3, name='option 3')
- self.assertHTMLEqual(ChoiceFieldForm().as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
+ self.assertHTMLEqual(
+ ChoiceFieldForm().as_p(),
+ """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
<option value="1" selected="selected">ChoiceOption 1</option>
<option value="2">ChoiceOption 2</option>
<option value="3">ChoiceOption 3</option>
@@ -111,28 +113,33 @@ class ModelFormCallableModelDefault(TestCase):
<option value="2">ChoiceOption 2</option>
<option value="3">ChoiceOption 3</option>
</select><input type="hidden" name="initial-choice_int" value="1" id="initial-id_choice_int" /></p>
-<p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice">
+<p><label for="id_multi_choice">Multi choice:</label>
+<select multiple="multiple" name="multi_choice" id="id_multi_choice">
<option value="1" selected="selected">ChoiceOption 1</option>
<option value="2">ChoiceOption 2</option>
<option value="3">ChoiceOption 3</option>
</select><input type="hidden" name="initial-multi_choice" value="1" id="initial-id_multi_choice_0" /></p>
-<p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int">
+<p><label for="id_multi_choice_int">Multi choice int:</label>
+<select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int">
<option value="1" selected="selected">ChoiceOption 1</option>
<option value="2">ChoiceOption 2</option>
<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-multi_choice_int" value="1" id="initial-id_multi_choice_int_0" /></p>""")
+</select><input type="hidden" name="initial-multi_choice_int" value="1" id="initial-id_multi_choice_int_0" /></p>"""
+ )
def test_initial_instance_value(self):
"Initial instances for model fields may also be instances (refs #7287)"
ChoiceOptionModel.objects.create(id=1, name='default')
obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
- self.assertHTMLEqual(ChoiceFieldForm(initial={
- 'choice': obj2,
- 'choice_int': obj2,
- 'multi_choice': [obj2, obj3],
- 'multi_choice_int': ChoiceOptionModel.objects.exclude(name="default"),
- }).as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
+ self.assertHTMLEqual(
+ ChoiceFieldForm(initial={
+ 'choice': obj2,
+ 'choice_int': obj2,
+ 'multi_choice': [obj2, obj3],
+ 'multi_choice_int': ChoiceOptionModel.objects.exclude(name="default"),
+ }).as_p(),
+ """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
<option value="1">ChoiceOption 1</option>
<option value="2" selected="selected">ChoiceOption 2</option>
<option value="3">ChoiceOption 3</option>
@@ -142,24 +149,28 @@ class ModelFormCallableModelDefault(TestCase):
<option value="2" selected="selected">ChoiceOption 2</option>
<option value="3">ChoiceOption 3</option>
</select><input type="hidden" name="initial-choice_int" value="2" id="initial-id_choice_int" /></p>
-<p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice">
+<p><label for="id_multi_choice">Multi choice:</label>
+<select multiple="multiple" name="multi_choice" id="id_multi_choice">
<option value="1">ChoiceOption 1</option>
<option value="2" selected="selected">ChoiceOption 2</option>
<option value="3" selected="selected">ChoiceOption 3</option>
</select><input type="hidden" name="initial-multi_choice" value="2" id="initial-id_multi_choice_0" />
<input type="hidden" name="initial-multi_choice" value="3" id="initial-id_multi_choice_1" /></p>
-<p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int">
+<p><label for="id_multi_choice_int">Multi choice int:</label>
+<select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int">
<option value="1">ChoiceOption 1</option>
<option value="2" selected="selected">ChoiceOption 2</option>
<option value="3" selected="selected">ChoiceOption 3</option>
</select><input type="hidden" name="initial-multi_choice_int" value="2" id="initial-id_multi_choice_int_0" />
-<input type="hidden" name="initial-multi_choice_int" value="3" id="initial-id_multi_choice_int_1" /></p>""")
+<input type="hidden" name="initial-multi_choice_int" value="3" id="initial-id_multi_choice_int_1" /></p>"""
+ )
class FormsModelTestCase(TestCase):
def test_unicode_filename(self):
# FileModel with unicode filename and data #########################
- f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False)
+ file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))
+ f = FileForm(data={}, files={'file1': file1}, auto_id=False)
self.assertTrue(f.is_valid())
self.assertIn('file1', f.cleaned_data)
m = FileModel.objects.create(file=f.cleaned_data['file1'])
@@ -287,23 +298,28 @@ class ManyToManyExclusionTestCase(TestCase):
class EmptyLabelTestCase(TestCase):
def test_empty_field_char(self):
f = EmptyCharLabelChoiceForm()
- self.assertHTMLEqual(f.as_p(),
+ self.assertHTMLEqual(
+ f.as_p(),
"""<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" /></p>
<p><label for="id_choice">Choice:</label> <select id="id_choice" name="choice">
<option value="" selected="selected">No Preference</option>
<option value="f">Foo</option>
<option value="b">Bar</option>
-</select></p>""")
+</select></p>"""
+ )
def test_empty_field_char_none(self):
f = EmptyCharLabelNoneChoiceForm()
- self.assertHTMLEqual(f.as_p(),
+ self.assertHTMLEqual(
+ f.as_p(),
"""<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" /></p>
-<p><label for="id_choice_string_w_none">Choice string w none:</label> <select id="id_choice_string_w_none" name="choice_string_w_none">
+<p><label for="id_choice_string_w_none">Choice string w none:</label>
+<select id="id_choice_string_w_none" name="choice_string_w_none">
<option value="" selected="selected">No Preference</option>
<option value="f">Foo</option>
<option value="b">Bar</option>
-</select></p>""")
+</select></p>"""
+ )
def test_save_empty_label_forms(self):
# Test that saving a form with a blank choice results in the expected
@@ -324,13 +340,16 @@ class EmptyLabelTestCase(TestCase):
def test_empty_field_integer(self):
f = EmptyIntegerLabelChoiceForm()
- self.assertHTMLEqual(f.as_p(),
+ self.assertHTMLEqual(
+ f.as_p(),
"""<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" /></p>
-<p><label for="id_choice_integer">Choice integer:</label> <select id="id_choice_integer" name="choice_integer">
+<p><label for="id_choice_integer">Choice integer:</label>
+<select id="id_choice_integer" name="choice_integer">
<option value="" selected="selected">No Preference</option>
<option value="1">Foo</option>
<option value="2">Bar</option>
-</select></p>""")
+</select></p>"""
+ )
def test_get_display_value_on_none(self):
m = ChoiceModel.objects.create(name='test', choice='', choice_integer=None)
@@ -340,20 +359,28 @@ class EmptyLabelTestCase(TestCase):
def test_html_rendering_of_prepopulated_models(self):
none_model = ChoiceModel(name='none-test', choice_integer=None)
f = EmptyIntegerLabelChoiceForm(instance=none_model)
- self.assertHTMLEqual(f.as_p(),
- """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" value="none-test"/></p>
-<p><label for="id_choice_integer">Choice integer:</label> <select id="id_choice_integer" name="choice_integer">
+ self.assertHTMLEqual(
+ f.as_p(),
+ """<p><label for="id_name">Name:</label>
+<input id="id_name" maxlength="10" name="name" type="text" value="none-test"/></p>
+<p><label for="id_choice_integer">Choice integer:</label>
+<select id="id_choice_integer" name="choice_integer">
<option value="" selected="selected">No Preference</option>
<option value="1">Foo</option>
<option value="2">Bar</option>
-</select></p>""")
+</select></p>"""
+ )
foo_model = ChoiceModel(name='foo-test', choice_integer=1)
f = EmptyIntegerLabelChoiceForm(instance=foo_model)
- self.assertHTMLEqual(f.as_p(),
- """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" value="foo-test"/></p>
-<p><label for="id_choice_integer">Choice integer:</label> <select id="id_choice_integer" name="choice_integer">
+ self.assertHTMLEqual(
+ f.as_p(),
+ """<p><label for="id_name">Name:</label>
+<input id="id_name" maxlength="10" name="name" type="text" value="foo-test"/></p>
+<p><label for="id_choice_integer">Choice integer:</label>
+<select id="id_choice_integer" name="choice_integer">
<option value="">No Preference</option>
<option value="1" selected="selected">Foo</option>
<option value="2">Bar</option>
-</select></p>""")
+</select></p>"""
+ )