From 9c19aff7c7561e3a82978a272ecdaad40dda5c00 Mon Sep 17 00:00:00 2001
From: django-bot
Date: Thu, 3 Feb 2022 20:24:19 +0100
Subject: Refs #33476 -- Reformatted code with Black.
---
tests/forms_tests/field_tests/__init__.py | 4 +-
tests/forms_tests/field_tests/test_base.py | 13 +-
tests/forms_tests/field_tests/test_booleanfield.py | 47 +-
tests/forms_tests/field_tests/test_charfield.py | 100 +-
tests/forms_tests/field_tests/test_choicefield.py | 73 +-
tests/forms_tests/field_tests/test_combofield.py | 37 +-
tests/forms_tests/field_tests/test_datefield.py | 183 +-
.../forms_tests/field_tests/test_datetimefield.py | 125 +-
tests/forms_tests/field_tests/test_decimalfield.py | 193 +-
.../forms_tests/field_tests/test_durationfield.py | 37 +-
tests/forms_tests/field_tests/test_emailfield.py | 55 +-
tests/forms_tests/field_tests/test_filefield.py | 88 +-
.../forms_tests/field_tests/test_filepathfield.py | 105 +-
tests/forms_tests/field_tests/test_floatfield.py | 85 +-
.../field_tests/test_genericipaddressfield.py | 219 +-
tests/forms_tests/field_tests/test_imagefield.py | 74 +-
tests/forms_tests/field_tests/test_integerfield.py | 112 +-
tests/forms_tests/field_tests/test_jsonfield.py | 71 +-
.../field_tests/test_multiplechoicefield.py | 75 +-
.../field_tests/test_multivaluefield.py | 115 +-
.../field_tests/test_nullbooleanfield.py | 52 +-
tests/forms_tests/field_tests/test_regexfield.py | 92 +-
tests/forms_tests/field_tests/test_slugfield.py | 23 +-
.../field_tests/test_splitdatetimefield.py | 75 +-
tests/forms_tests/field_tests/test_timefield.py | 31 +-
.../field_tests/test_typedchoicefield.py | 62 +-
.../field_tests/test_typedmultiplechoicefield.py | 44 +-
tests/forms_tests/field_tests/test_urlfield.py | 116 +-
tests/forms_tests/field_tests/test_uuidfield.py | 19 +-
tests/forms_tests/models.py | 44 +-
tests/forms_tests/tests/__init__.py | 6 +-
tests/forms_tests/tests/test_deprecation_forms.py | 67 +-
tests/forms_tests/tests/test_error_messages.py | 322 +--
tests/forms_tests/tests/test_forms.py | 2574 ++++++++++++--------
tests/forms_tests/tests/test_formsets.py | 1185 +++++----
tests/forms_tests/tests/test_i18n.py | 62 +-
tests/forms_tests/tests/test_input_formats.py | 304 +--
tests/forms_tests/tests/test_media.py | 412 ++--
tests/forms_tests/tests/test_renderers.py | 24 +-
tests/forms_tests/tests/test_utils.py | 215 +-
tests/forms_tests/tests/test_validators.py | 122 +-
tests/forms_tests/tests/test_widgets.py | 11 +-
tests/forms_tests/tests/tests.py | 200 +-
tests/forms_tests/urls.py | 4 +-
tests/forms_tests/views.py | 8 +-
tests/forms_tests/widget_tests/base.py | 22 +-
.../forms_tests/widget_tests/test_checkboxinput.py | 89 +-
.../widget_tests/test_checkboxselectmultiple.py | 100 +-
.../widget_tests/test_clearablefileinput.py | 101 +-
tests/forms_tests/widget_tests/test_dateinput.py | 43 +-
.../forms_tests/widget_tests/test_datetimeinput.py | 74 +-
tests/forms_tests/widget_tests/test_fileinput.py | 23 +-
tests/forms_tests/widget_tests/test_hiddeninput.py | 8 +-
tests/forms_tests/widget_tests/test_input.py | 20 +-
.../widget_tests/test_multiplehiddeninput.py | 44 +-
tests/forms_tests/widget_tests/test_multiwidget.py | 203 +-
.../widget_tests/test_nullbooleanselect.py | 112 +-
tests/forms_tests/widget_tests/test_numberinput.py | 9 +-
.../forms_tests/widget_tests/test_passwordinput.py | 23 +-
tests/forms_tests/widget_tests/test_radioselect.py | 69 +-
tests/forms_tests/widget_tests/test_select.py | 375 +--
.../widget_tests/test_selectdatewidget.py | 240 +-
.../widget_tests/test_selectmultiple.py | 140 +-
.../widget_tests/test_splitdatetimewidget.py | 93 +-
.../widget_tests/test_splithiddendatetimewidget.py | 83 +-
tests/forms_tests/widget_tests/test_textarea.py | 52 +-
tests/forms_tests/widget_tests/test_textinput.py | 79 +-
tests/forms_tests/widget_tests/test_timeinput.py | 55 +-
tests/forms_tests/widget_tests/test_widget.py | 23 +-
69 files changed, 5893 insertions(+), 4072 deletions(-)
(limited to 'tests/forms_tests')
diff --git a/tests/forms_tests/field_tests/__init__.py b/tests/forms_tests/field_tests/__init__.py
index 4aae30282b..94b2a91242 100644
--- a/tests/forms_tests/field_tests/__init__.py
+++ b/tests/forms_tests/field_tests/__init__.py
@@ -2,8 +2,8 @@ from django import forms
class FormFieldAssertionsMixin:
-
def assertWidgetRendersTo(self, field, to):
class Form(forms.Form):
f = field
- self.assertHTMLEqual(str(Form()['f']), to)
+
+ self.assertHTMLEqual(str(Form()["f"]), to)
diff --git a/tests/forms_tests/field_tests/test_base.py b/tests/forms_tests/field_tests/test_base.py
index 4ddbea3414..201e05e47e 100644
--- a/tests/forms_tests/field_tests/test_base.py
+++ b/tests/forms_tests/field_tests/test_base.py
@@ -3,7 +3,6 @@ from django.test import SimpleTestCase
class BasicFieldsTests(SimpleTestCase):
-
def test_field_sets_widget_is_required(self):
self.assertTrue(Field(required=True).widget.is_required)
self.assertFalse(Field(required=False).widget.is_required)
@@ -23,20 +22,20 @@ class BasicFieldsTests(SimpleTestCase):
def test_field_deepcopies_widget_instance(self):
class CustomChoiceField(ChoiceField):
- widget = Select(attrs={'class': 'my-custom-class'})
+ widget = Select(attrs={"class": "my-custom-class"})
class TestForm(Form):
field1 = CustomChoiceField(choices=[])
field2 = CustomChoiceField(choices=[])
f = TestForm()
- f.fields['field1'].choices = [('1', '1')]
- f.fields['field2'].choices = [('2', '2')]
- self.assertEqual(f.fields['field1'].widget.choices, [('1', '1')])
- self.assertEqual(f.fields['field2'].widget.choices, [('2', '2')])
+ f.fields["field1"].choices = [("1", "1")]
+ f.fields["field2"].choices = [("2", "2")]
+ self.assertEqual(f.fields["field1"].widget.choices, [("1", "1")])
+ self.assertEqual(f.fields["field2"].widget.choices, [("2", "2")])
class DisabledFieldTests(SimpleTestCase):
def test_disabled_field_has_changed_always_false(self):
disabled_field = Field(disabled=True)
- self.assertFalse(disabled_field.has_changed('x', 'y'))
+ self.assertFalse(disabled_field.has_changed("x", "y"))
diff --git a/tests/forms_tests/field_tests/test_booleanfield.py b/tests/forms_tests/field_tests/test_booleanfield.py
index b0153e9e0b..560a0f473b 100644
--- a/tests/forms_tests/field_tests/test_booleanfield.py
+++ b/tests/forms_tests/field_tests/test_booleanfield.py
@@ -6,11 +6,10 @@ from django.test import SimpleTestCase
class BooleanFieldTest(SimpleTestCase):
-
def test_booleanfield_clean_1(self):
f = BooleanField()
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
- f.clean('')
+ f.clean("")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.assertTrue(f.clean(True))
@@ -19,25 +18,25 @@ class BooleanFieldTest(SimpleTestCase):
self.assertTrue(f.clean(1))
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(0)
- self.assertTrue(f.clean('Django rocks'))
- self.assertTrue(f.clean('True'))
+ self.assertTrue(f.clean("Django rocks"))
+ self.assertTrue(f.clean("True"))
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
- f.clean('False')
+ f.clean("False")
def test_booleanfield_clean_2(self):
f = BooleanField(required=False)
- self.assertIs(f.clean(''), False)
+ self.assertIs(f.clean(""), False)
self.assertIs(f.clean(None), False)
self.assertIs(f.clean(True), True)
self.assertIs(f.clean(False), False)
self.assertIs(f.clean(1), True)
self.assertIs(f.clean(0), False)
- self.assertIs(f.clean('1'), True)
- self.assertIs(f.clean('0'), False)
- self.assertIs(f.clean('Django rocks'), True)
- self.assertIs(f.clean('False'), False)
- self.assertIs(f.clean('false'), False)
- self.assertIs(f.clean('FaLsE'), False)
+ self.assertIs(f.clean("1"), True)
+ self.assertIs(f.clean("0"), False)
+ self.assertIs(f.clean("Django rocks"), True)
+ self.assertIs(f.clean("False"), False)
+ self.assertIs(f.clean("false"), False)
+ self.assertIs(f.clean("FaLsE"), False)
def test_boolean_picklable(self):
self.assertIsInstance(pickle.loads(pickle.dumps(BooleanField())), BooleanField)
@@ -45,20 +44,20 @@ class BooleanFieldTest(SimpleTestCase):
def test_booleanfield_changed(self):
f = BooleanField()
self.assertFalse(f.has_changed(None, None))
- self.assertFalse(f.has_changed(None, ''))
- self.assertFalse(f.has_changed('', None))
- self.assertFalse(f.has_changed('', ''))
- self.assertTrue(f.has_changed(False, 'on'))
- self.assertFalse(f.has_changed(True, 'on'))
- self.assertTrue(f.has_changed(True, ''))
+ self.assertFalse(f.has_changed(None, ""))
+ self.assertFalse(f.has_changed("", None))
+ self.assertFalse(f.has_changed("", ""))
+ self.assertTrue(f.has_changed(False, "on"))
+ self.assertFalse(f.has_changed(True, "on"))
+ self.assertTrue(f.has_changed(True, ""))
# Initial value may have mutated to a string due to show_hidden_initial (#19537)
- self.assertTrue(f.has_changed('False', 'on'))
+ self.assertTrue(f.has_changed("False", "on"))
# HiddenInput widget sends string values for boolean but doesn't clean them in value_from_datadict
- self.assertFalse(f.has_changed(False, 'False'))
- self.assertFalse(f.has_changed(True, 'True'))
- self.assertTrue(f.has_changed(False, 'True'))
- self.assertTrue(f.has_changed(True, 'False'))
+ self.assertFalse(f.has_changed(False, "False"))
+ self.assertFalse(f.has_changed(True, "True"))
+ self.assertTrue(f.has_changed(False, "True"))
+ self.assertTrue(f.has_changed(True, "False"))
def test_disabled_has_changed(self):
f = BooleanField(disabled=True)
- self.assertIs(f.has_changed('True', 'False'), False)
+ self.assertIs(f.has_changed("True", "False"), False)
diff --git a/tests/forms_tests/field_tests/test_charfield.py b/tests/forms_tests/field_tests/test_charfield.py
index 352761deec..2c3f9b7ebe 100644
--- a/tests/forms_tests/field_tests/test_charfield.py
+++ b/tests/forms_tests/field_tests/test_charfield.py
@@ -1,66 +1,63 @@
from django.core.exceptions import ValidationError
-from django.forms import (
- CharField, HiddenInput, PasswordInput, Textarea, TextInput,
-)
+from django.forms import CharField, HiddenInput, PasswordInput, Textarea, TextInput
from django.test import SimpleTestCase
from . import FormFieldAssertionsMixin
class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
-
def test_charfield_1(self):
f = CharField()
- self.assertEqual('1', f.clean(1))
- self.assertEqual('hello', f.clean('hello'))
+ self.assertEqual("1", f.clean(1))
+ self.assertEqual("hello", f.clean("hello"))
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
- f.clean('')
- self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3]))
+ f.clean("")
+ self.assertEqual("[1, 2, 3]", f.clean([1, 2, 3]))
self.assertIsNone(f.max_length)
self.assertIsNone(f.min_length)
def test_charfield_2(self):
f = CharField(required=False)
- self.assertEqual('1', f.clean(1))
- self.assertEqual('hello', f.clean('hello'))
- self.assertEqual('', f.clean(None))
- self.assertEqual('', f.clean(''))
- self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3]))
+ self.assertEqual("1", f.clean(1))
+ self.assertEqual("hello", f.clean("hello"))
+ self.assertEqual("", f.clean(None))
+ self.assertEqual("", f.clean(""))
+ self.assertEqual("[1, 2, 3]", f.clean([1, 2, 3]))
self.assertIsNone(f.max_length)
self.assertIsNone(f.min_length)
def test_charfield_3(self):
f = CharField(max_length=10, required=False)
- self.assertEqual('12345', f.clean('12345'))
- self.assertEqual('1234567890', f.clean('1234567890'))
+ self.assertEqual("12345", f.clean("12345"))
+ self.assertEqual("1234567890", f.clean("1234567890"))
msg = "'Ensure this value has at most 10 characters (it has 11).'"
with self.assertRaisesMessage(ValidationError, msg):
- f.clean('1234567890a')
+ f.clean("1234567890a")
self.assertEqual(f.max_length, 10)
self.assertIsNone(f.min_length)
def test_charfield_4(self):
f = CharField(min_length=10, required=False)
- self.assertEqual('', f.clean(''))
+ self.assertEqual("", f.clean(""))
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'))
+ f.clean("12345")
+ self.assertEqual("1234567890", f.clean("1234567890"))
+ self.assertEqual("1234567890a", f.clean("1234567890a"))
self.assertIsNone(f.max_length)
self.assertEqual(f.min_length, 10)
def test_charfield_5(self):
f = CharField(min_length=10, required=True)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
- f.clean('')
+ f.clean("")
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'))
+ f.clean("12345")
+ self.assertEqual("1234567890", f.clean("1234567890"))
+ self.assertEqual("1234567890a", f.clean("1234567890a"))
self.assertIsNone(f.max_length)
self.assertEqual(f.min_length, 10)
@@ -70,12 +67,12 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
raises an exception.
"""
with self.assertRaises(ValueError):
- CharField(min_length='a')
+ CharField(min_length="a")
with self.assertRaises(ValueError):
- CharField(max_length='a')
- msg = '__init__() takes 1 positional argument but 2 were given'
+ CharField(max_length="a")
+ msg = "__init__() takes 1 positional argument but 2 were given"
with self.assertRaisesMessage(TypeError, msg):
- CharField('a')
+ CharField("a")
def test_charfield_widget_attrs(self):
"""
@@ -90,22 +87,28 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
# Return a maxlength attribute equal to max_length.
f = CharField(max_length=10)
- self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'})
- self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'})
- self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10'})
+ self.assertEqual(f.widget_attrs(TextInput()), {"maxlength": "10"})
+ self.assertEqual(f.widget_attrs(PasswordInput()), {"maxlength": "10"})
+ self.assertEqual(f.widget_attrs(Textarea()), {"maxlength": "10"})
# Return a minlength attribute equal to min_length.
f = CharField(min_length=5)
- self.assertEqual(f.widget_attrs(TextInput()), {'minlength': '5'})
- self.assertEqual(f.widget_attrs(PasswordInput()), {'minlength': '5'})
- self.assertEqual(f.widget_attrs(Textarea()), {'minlength': '5'})
+ self.assertEqual(f.widget_attrs(TextInput()), {"minlength": "5"})
+ self.assertEqual(f.widget_attrs(PasswordInput()), {"minlength": "5"})
+ self.assertEqual(f.widget_attrs(Textarea()), {"minlength": "5"})
# Return both maxlength and minlength when both max_length and
# min_length are set.
f = CharField(max_length=10, min_length=5)
- self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10', 'minlength': '5'})
- self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10', 'minlength': '5'})
- self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10', 'minlength': '5'})
+ self.assertEqual(
+ f.widget_attrs(TextInput()), {"maxlength": "10", "minlength": "5"}
+ )
+ self.assertEqual(
+ f.widget_attrs(PasswordInput()), {"maxlength": "10", "minlength": "5"}
+ )
+ self.assertEqual(
+ f.widget_attrs(Textarea()), {"maxlength": "10", "minlength": "5"}
+ )
self.assertEqual(f.widget_attrs(HiddenInput()), {})
def test_charfield_strip(self):
@@ -113,12 +116,12 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
Values have whitespace stripped but not if strip=False.
"""
f = CharField()
- self.assertEqual(f.clean(' 1'), '1')
- self.assertEqual(f.clean('1 '), '1')
+ self.assertEqual(f.clean(" 1"), "1")
+ self.assertEqual(f.clean("1 "), "1")
f = CharField(strip=False)
- self.assertEqual(f.clean(' 1'), ' 1')
- self.assertEqual(f.clean('1 '), '1 ')
+ self.assertEqual(f.clean(" 1"), " 1")
+ self.assertEqual(f.clean("1 "), "1 ")
def test_strip_before_checking_empty(self):
"""
@@ -126,10 +129,11 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
converted to the empty value, None.
"""
f = CharField(required=False, empty_value=None)
- self.assertIsNone(f.clean(' '))
+ self.assertIsNone(f.clean(" "))
def test_clean_non_string(self):
"""CharField.clean() calls str(value) before stripping it."""
+
class StringWrapper:
def __init__(self, v):
self.v = v
@@ -137,18 +141,20 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def __str__(self):
return self.v
- value = StringWrapper(' ')
+ value = StringWrapper(" ")
f1 = CharField(required=False, empty_value=None)
self.assertIsNone(f1.clean(value))
f2 = CharField(strip=False)
- self.assertEqual(f2.clean(value), ' ')
+ self.assertEqual(f2.clean(value), " ")
def test_charfield_disabled(self):
f = CharField(disabled=True)
- self.assertWidgetRendersTo(f, '')
+ self.assertWidgetRendersTo(
+ f, ''
+ )
def test_null_characters_prohibited(self):
f = CharField()
- msg = 'Null characters are not allowed.'
+ msg = "Null characters are not allowed."
with self.assertRaisesMessage(ValidationError, msg):
- f.clean('\x00something')
+ f.clean("\x00something")
diff --git a/tests/forms_tests/field_tests/test_choicefield.py b/tests/forms_tests/field_tests/test_choicefield.py
index f25e2cedfd..bc580bbf02 100644
--- a/tests/forms_tests/field_tests/test_choicefield.py
+++ b/tests/forms_tests/field_tests/test_choicefield.py
@@ -7,52 +7,52 @@ from . import FormFieldAssertionsMixin
class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
-
def test_choicefield_1(self):
- f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')])
+ f = ChoiceField(choices=[("1", "One"), ("2", "Two")])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
- f.clean('')
+ f.clean("")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
- self.assertEqual('1', f.clean(1))
- self.assertEqual('1', f.clean('1'))
+ self.assertEqual("1", f.clean(1))
+ self.assertEqual("1", f.clean("1"))
msg = "'Select a valid choice. 3 is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
- f.clean('3')
+ f.clean("3")
def test_choicefield_2(self):
- f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
- self.assertEqual('', f.clean(''))
- self.assertEqual('', f.clean(None))
- self.assertEqual('1', f.clean(1))
- self.assertEqual('1', f.clean('1'))
+ f = ChoiceField(choices=[("1", "One"), ("2", "Two")], required=False)
+ self.assertEqual("", f.clean(""))
+ self.assertEqual("", f.clean(None))
+ self.assertEqual("1", f.clean(1))
+ self.assertEqual("1", f.clean("1"))
msg = "'Select a valid choice. 3 is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
- f.clean('3')
+ f.clean("3")
def test_choicefield_3(self):
- f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
- self.assertEqual('J', f.clean('J'))
+ f = ChoiceField(choices=[("J", "John"), ("P", "Paul")])
+ self.assertEqual("J", f.clean("J"))
msg = "'Select a valid choice. John is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
- f.clean('John')
+ f.clean("John")
def test_choicefield_4(self):
f = ChoiceField(
choices=[
- ('Numbers', (('1', 'One'), ('2', 'Two'))),
- ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other'),
+ ("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.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"))
msg = "'Select a valid choice. 6 is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
- f.clean('6')
+ f.clean("6")
def test_choicefield_choices_default(self):
f = ChoiceField()
@@ -60,9 +60,10 @@ class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_choicefield_callable(self):
def choices():
- return [('J', 'John'), ('P', 'Paul')]
+ return [("J", "John"), ("P", "Paul")]
+
f = ChoiceField(choices=choices)
- self.assertEqual('J', f.clean('J'))
+ self.assertEqual("J", f.clean("J"))
def test_choicefield_callable_may_evaluate_to_different_values(self):
choices = []
@@ -73,29 +74,29 @@ class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
class ChoiceFieldForm(Form):
choicefield = ChoiceField(choices=choices_as_callable)
- choices = [('J', 'John')]
+ choices = [("J", "John")]
form = ChoiceFieldForm()
- self.assertEqual([('J', 'John')], list(form.fields['choicefield'].choices))
+ self.assertEqual([("J", "John")], list(form.fields["choicefield"].choices))
- choices = [('P', 'Paul')]
+ choices = [("P", "Paul")]
form = ChoiceFieldForm()
- self.assertEqual([('P', 'Paul')], list(form.fields['choicefield'].choices))
+ self.assertEqual([("P", "Paul")], list(form.fields["choicefield"].choices))
def test_choicefield_disabled(self):
- f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')], disabled=True)
+ f = ChoiceField(choices=[("J", "John"), ("P", "Paul")], disabled=True)
self.assertWidgetRendersTo(
f,
''
+ '',
)
def test_choicefield_enumeration(self):
class FirstNames(models.TextChoices):
- JOHN = 'J', 'John'
- PAUL = 'P', 'Paul'
+ JOHN = "J", "John"
+ PAUL = "P", "Paul"
f = ChoiceField(choices=FirstNames.choices)
- self.assertEqual(f.clean('J'), 'J')
+ self.assertEqual(f.clean("J"), "J")
msg = "'Select a valid choice. 3 is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
- f.clean('3')
+ f.clean("3")
diff --git a/tests/forms_tests/field_tests/test_combofield.py b/tests/forms_tests/field_tests/test_combofield.py
index 481783fe2e..d433fdf2b3 100644
--- a/tests/forms_tests/field_tests/test_combofield.py
+++ b/tests/forms_tests/field_tests/test_combofield.py
@@ -4,25 +4,34 @@ from django.test import SimpleTestCase
class ComboFieldTest(SimpleTestCase):
-
def test_combofield_1(self):
f = ComboField(fields=[CharField(max_length=20), EmailField()])
- self.assertEqual('test@example.com', f.clean('test@example.com'))
- with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'"):
- f.clean('longemailaddress@example.com')
- with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"):
- f.clean('not an email')
+ self.assertEqual("test@example.com", f.clean("test@example.com"))
+ with self.assertRaisesMessage(
+ ValidationError,
+ "'Ensure this value has at most 20 characters (it has 28).'",
+ ):
+ f.clean("longemailaddress@example.com")
+ with self.assertRaisesMessage(
+ ValidationError, "'Enter a valid email address.'"
+ ):
+ f.clean("not an email")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
- f.clean('')
+ f.clean("")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
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'))
- with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'"):
- f.clean('longemailaddress@example.com')
- with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"):
- f.clean('not an email')
- self.assertEqual('', f.clean(''))
- self.assertEqual('', f.clean(None))
+ self.assertEqual("test@example.com", f.clean("test@example.com"))
+ with self.assertRaisesMessage(
+ ValidationError,
+ "'Ensure this value has at most 20 characters (it has 28).'",
+ ):
+ f.clean("longemailaddress@example.com")
+ with self.assertRaisesMessage(
+ ValidationError, "'Enter a valid email address.'"
+ ):
+ f.clean("not an email")
+ self.assertEqual("", f.clean(""))
+ self.assertEqual("", f.clean(None))
diff --git a/tests/forms_tests/field_tests/test_datefield.py b/tests/forms_tests/field_tests/test_datefield.py
index 10d77bf1bb..a9f93f40ed 100644
--- a/tests/forms_tests/field_tests/test_datefield.py
+++ b/tests/forms_tests/field_tests/test_datefield.py
@@ -11,174 +11,195 @@ class GetDate(Form):
class DateFieldTest(SimpleTestCase):
-
def test_form_field(self):
- a = GetDate({'mydate_month': '4', 'mydate_day': '1', 'mydate_year': '2008'})
+ a = GetDate({"mydate_month": "4", "mydate_day": "1", "mydate_year": "2008"})
self.assertTrue(a.is_valid())
- self.assertEqual(a.cleaned_data['mydate'], date(2008, 4, 1))
+ self.assertEqual(a.cleaned_data["mydate"], date(2008, 4, 1))
# As with any widget that implements get_value_from_datadict(), we must
# accept the input from the "as_hidden" rendering as well.
self.assertHTMLEqual(
- a['mydate'].as_hidden(),
+ a["mydate"].as_hidden(),
'',
)
- b = GetDate({'mydate': '2008-4-1'})
+ b = GetDate({"mydate": "2008-4-1"})
self.assertTrue(b.is_valid())
- self.assertEqual(b.cleaned_data['mydate'], date(2008, 4, 1))
+ self.assertEqual(b.cleaned_data["mydate"], date(2008, 4, 1))
# Invalid dates shouldn't be allowed
- c = GetDate({'mydate_month': '2', 'mydate_day': '31', 'mydate_year': '2010'})
+ c = GetDate({"mydate_month": "2", "mydate_day": "31", "mydate_year": "2010"})
self.assertFalse(c.is_valid())
- self.assertEqual(c.errors, {'mydate': ['Enter a valid date.']})
+ self.assertEqual(c.errors, {"mydate": ["Enter a valid date."]})
# label tag is correctly associated with month dropdown
- d = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'})
+ d = GetDate({"mydate_month": "1", "mydate_day": "1", "mydate_year": "2010"})
self.assertIn('
',
- help_text_html=' %s',
+ error_row="%s",
+ row_ender="",
+ help_text_html=" %s",
errors_on_separate_row=True,
)
@@ -40,11 +40,11 @@ class DeprecationTests(SimpleTestCase):
email = EmailField()
comment = CharField()
- data = {'email': 'invalid'}
+ data = {"email": "invalid"}
f = EmailForm(data, error_class=DivErrorList)
msg = (
- 'Returning a plain string from DivErrorList is deprecated. Please '
- 'customize via the template system instead.'
+ "Returning a plain string from DivErrorList is deprecated. Please "
+ "customize via the template system instead."
)
with self.assertRaisesMessage(RemovedInDjango50Warning, msg):
f.as_p()
@@ -58,7 +58,7 @@ class DeprecatedTests(SimpleTestCase):
email = EmailField()
comment = CharField()
- data = {'email': 'invalid'}
+ data = {"email": "invalid"}
f = CommentForm(data, auto_id=False, error_class=DivErrorList)
self.assertHTMLEqual(
f.as_p(),
@@ -73,15 +73,16 @@ class DeprecatedTests(SimpleTestCase):
def test_field_name(self):
"""#5749 - `field_name` may be used as a key in _html_output()."""
+
class SomeForm(Form):
some_field = CharField()
def as_p(self):
return self._html_output(
normal_row='',
- error_row='%s',
- row_ender='',
- help_text_html=' %s',
+ error_row="%s",
+ row_ender="",
+ help_text_html=" %s",
errors_on_separate_row=True,
)
@@ -92,15 +93,16 @@ class DeprecatedTests(SimpleTestCase):
"""
`css_classes` may be used as a key in _html_output() (empty classes).
"""
+
class SomeForm(Form):
some_field = CharField()
def as_p(self):
return self._html_output(
normal_row='',
- error_row='%s',
- row_ender='',
- help_text_html=' %s',
+ error_row="%s",
+ row_ender="",
+ help_text_html=" %s",
errors_on_separate_row=True,
)
@@ -112,16 +114,17 @@ class DeprecatedTests(SimpleTestCase):
`css_classes` may be used as a key in _html_output() (class comes
from required_css_class in this case).
"""
+
class SomeForm(Form):
some_field = CharField()
- required_css_class = 'foo'
+ required_css_class = "foo"
def as_p(self):
return self._html_output(
normal_row='',
- error_row='%s',
- row_ender='',
- help_text_html=' %s',
+ error_row="%s",
+ row_ender="",
+ help_text_html=" %s",
errors_on_separate_row=True,
)
@@ -133,6 +136,7 @@ class DeprecatedTests(SimpleTestCase):
BaseForm._html_output() should merge all the hidden input fields and
put them in the last row.
"""
+
class SomeForm(Form):
hidden1 = CharField(widget=HiddenInput)
custom = CharField()
@@ -140,10 +144,10 @@ class DeprecatedTests(SimpleTestCase):
def as_p(self):
return self._html_output(
- normal_row='
'
+ '',
)
def test_field_name_with_hidden_input_and_non_matching_row_ender(self):
@@ -160,6 +164,7 @@ class DeprecatedTests(SimpleTestCase):
BaseForm._html_output() should merge all the hidden input fields and
put them in the last row ended with the specific row ender.
"""
+
class SomeForm(Form):
hidden1 = CharField(widget=HiddenInput)
custom = CharField()
@@ -167,10 +172,10 @@ class DeprecatedTests(SimpleTestCase):
def as_p(self):
return self._html_output(
- normal_row='
\n'
''
- ''
+ '',
)
diff --git a/tests/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py
index 340c39546c..2ad356858f 100644
--- a/tests/forms_tests/tests/test_error_messages.py
+++ b/tests/forms_tests/tests/test_error_messages.py
@@ -1,11 +1,26 @@
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import (
- BooleanField, CharField, ChoiceField, DateField, DateTimeField,
- DecimalField, EmailField, FileField, FloatField, Form,
- GenericIPAddressField, IntegerField, ModelChoiceField,
- ModelMultipleChoiceField, MultipleChoiceField, RegexField,
- SplitDateTimeField, TimeField, URLField, utils,
+ BooleanField,
+ CharField,
+ ChoiceField,
+ DateField,
+ DateTimeField,
+ DecimalField,
+ EmailField,
+ FileField,
+ FloatField,
+ Form,
+ GenericIPAddressField,
+ IntegerField,
+ ModelChoiceField,
+ ModelMultipleChoiceField,
+ MultipleChoiceField,
+ RegexField,
+ SplitDateTimeField,
+ TimeField,
+ URLField,
+ utils,
)
from django.template import Context, Template
from django.test import SimpleTestCase, TestCase
@@ -24,188 +39,188 @@ class AssertFormErrorsMixin:
class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin):
def test_charfield(self):
e = {
- 'required': 'REQUIRED',
- 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s',
- 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s',
+ "required": "REQUIRED",
+ "min_length": "LENGTH %(show_value)s, MIN LENGTH %(limit_value)s",
+ "max_length": "LENGTH %(show_value)s, MAX LENGTH %(limit_value)s",
}
f = CharField(min_length=5, max_length=10, error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234')
- self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["LENGTH 4, MIN LENGTH 5"], f.clean, "1234")
+ self.assertFormErrors(["LENGTH 11, MAX LENGTH 10"], f.clean, "12345678901")
def test_integerfield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
- 'min_value': 'MIN VALUE IS %(limit_value)s',
- 'max_value': 'MAX VALUE IS %(limit_value)s',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
+ "min_value": "MIN VALUE IS %(limit_value)s",
+ "max_value": "MAX VALUE IS %(limit_value)s",
}
f = IntegerField(min_value=5, max_value=10, error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abc')
- self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
- self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID"], f.clean, "abc")
+ self.assertFormErrors(["MIN VALUE IS 5"], f.clean, "4")
+ self.assertFormErrors(["MAX VALUE IS 10"], f.clean, "11")
def test_floatfield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
- 'min_value': 'MIN VALUE IS %(limit_value)s',
- 'max_value': 'MAX VALUE IS %(limit_value)s',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
+ "min_value": "MIN VALUE IS %(limit_value)s",
+ "max_value": "MAX VALUE IS %(limit_value)s",
}
f = FloatField(min_value=5, max_value=10, error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abc')
- self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
- self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID"], f.clean, "abc")
+ self.assertFormErrors(["MIN VALUE IS 5"], f.clean, "4")
+ self.assertFormErrors(["MAX VALUE IS 10"], f.clean, "11")
def test_decimalfield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
- 'min_value': 'MIN VALUE IS %(limit_value)s',
- 'max_value': 'MAX VALUE IS %(limit_value)s',
- 'max_digits': 'MAX DIGITS IS %(max)s',
- 'max_decimal_places': 'MAX DP IS %(max)s',
- 'max_whole_digits': 'MAX DIGITS BEFORE DP IS %(max)s',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
+ "min_value": "MIN VALUE IS %(limit_value)s",
+ "max_value": "MAX VALUE IS %(limit_value)s",
+ "max_digits": "MAX DIGITS IS %(max)s",
+ "max_decimal_places": "MAX DP IS %(max)s",
+ "max_whole_digits": "MAX DIGITS BEFORE DP IS %(max)s",
}
f = DecimalField(min_value=5, max_value=10, error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abc')
- self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
- self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID"], f.clean, "abc")
+ self.assertFormErrors(["MIN VALUE IS 5"], f.clean, "4")
+ self.assertFormErrors(["MAX VALUE IS 10"], f.clean, "11")
f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e)
- self.assertFormErrors(['MAX DIGITS IS 4'], f2.clean, '123.45')
- self.assertFormErrors(['MAX DP IS 2'], f2.clean, '1.234')
- self.assertFormErrors(['MAX DIGITS BEFORE DP IS 2'], f2.clean, '123.4')
+ self.assertFormErrors(["MAX DIGITS IS 4"], f2.clean, "123.45")
+ self.assertFormErrors(["MAX DP IS 2"], f2.clean, "1.234")
+ self.assertFormErrors(["MAX DIGITS BEFORE DP IS 2"], f2.clean, "123.4")
def test_datefield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
}
f = DateField(error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abc')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID"], f.clean, "abc")
def test_timefield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
}
f = TimeField(error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abc')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID"], f.clean, "abc")
def test_datetimefield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
}
f = DateTimeField(error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abc')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID"], f.clean, "abc")
def test_regexfield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
- 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s',
- 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
+ "min_length": "LENGTH %(show_value)s, MIN LENGTH %(limit_value)s",
+ "max_length": "LENGTH %(show_value)s, MAX LENGTH %(limit_value)s",
}
- f = RegexField(r'^[0-9]+$', min_length=5, max_length=10, error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abcde')
- self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234')
- self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901')
+ f = RegexField(r"^[0-9]+$", min_length=5, max_length=10, error_messages=e)
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID"], f.clean, "abcde")
+ self.assertFormErrors(["LENGTH 4, MIN LENGTH 5"], f.clean, "1234")
+ self.assertFormErrors(["LENGTH 11, MAX LENGTH 10"], f.clean, "12345678901")
def test_emailfield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
- 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s',
- 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
+ "min_length": "LENGTH %(show_value)s, MIN LENGTH %(limit_value)s",
+ "max_length": "LENGTH %(show_value)s, MAX LENGTH %(limit_value)s",
}
f = EmailField(min_length=8, max_length=10, error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abcdefgh')
- self.assertFormErrors(['LENGTH 7, MIN LENGTH 8'], f.clean, 'a@b.com')
- self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, 'aye@bee.com')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID"], f.clean, "abcdefgh")
+ self.assertFormErrors(["LENGTH 7, MIN LENGTH 8"], f.clean, "a@b.com")
+ self.assertFormErrors(["LENGTH 11, MAX LENGTH 10"], f.clean, "aye@bee.com")
def test_filefield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
- 'missing': 'MISSING',
- 'empty': 'EMPTY FILE',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
+ "missing": "MISSING",
+ "empty": "EMPTY FILE",
}
f = FileField(error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abc')
- self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None))
- self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', ''))
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID"], f.clean, "abc")
+ self.assertFormErrors(["EMPTY FILE"], f.clean, SimpleUploadedFile("name", None))
+ self.assertFormErrors(["EMPTY FILE"], f.clean, SimpleUploadedFile("name", ""))
def test_urlfield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID',
- 'max_length': '"%(value)s" has more than %(limit_value)d characters.',
+ "required": "REQUIRED",
+ "invalid": "INVALID",
+ "max_length": '"%(value)s" has more than %(limit_value)d characters.',
}
f = URLField(error_messages=e, max_length=17)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID'], f.clean, 'abc.c')
+ 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'
+ "djangoproject.com",
)
def test_booleanfield(self):
e = {
- 'required': 'REQUIRED',
+ "required": "REQUIRED",
}
f = BooleanField(error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
def test_choicefield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid_choice': '%(value)s IS INVALID CHOICE',
+ "required": "REQUIRED",
+ "invalid_choice": "%(value)s IS INVALID CHOICE",
}
- f = ChoiceField(choices=[('a', 'aye')], error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, 'b')
+ f = ChoiceField(choices=[("a", "aye")], error_messages=e)
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["b IS INVALID CHOICE"], f.clean, "b")
def test_multiplechoicefield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid_choice': '%(value)s IS INVALID CHOICE',
- 'invalid_list': 'NOT A LIST',
+ "required": "REQUIRED",
+ "invalid_choice": "%(value)s IS INVALID CHOICE",
+ "invalid_list": "NOT A LIST",
}
- f = MultipleChoiceField(choices=[('a', 'aye')], error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['NOT A LIST'], f.clean, 'b')
- self.assertFormErrors(['b IS INVALID CHOICE'], f.clean, ['b'])
+ f = MultipleChoiceField(choices=[("a", "aye")], error_messages=e)
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["NOT A LIST"], f.clean, "b")
+ self.assertFormErrors(["b IS INVALID CHOICE"], f.clean, ["b"])
def test_splitdatetimefield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid_date': 'INVALID DATE',
- 'invalid_time': 'INVALID TIME',
+ "required": "REQUIRED",
+ "invalid_date": "INVALID DATE",
+ "invalid_time": "INVALID TIME",
}
f = SplitDateTimeField(error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID DATE', 'INVALID TIME'], f.clean, ['a', 'b'])
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID DATE", "INVALID TIME"], f.clean, ["a", "b"])
def test_generic_ipaddressfield(self):
e = {
- 'required': 'REQUIRED',
- 'invalid': 'INVALID IP ADDRESS',
+ "required": "REQUIRED",
+ "invalid": "INVALID IP ADDRESS",
}
f = GenericIPAddressField(error_messages=e)
- self.assertFormErrors(['REQUIRED'], f.clean, '')
- self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0')
+ self.assertFormErrors(["REQUIRED"], f.clean, "")
+ self.assertFormErrors(["INVALID IP ADDRESS"], f.clean, "127.0.0")
def test_subclassing_errorlist(self):
class TestForm(Form):
@@ -222,102 +237,113 @@ class FormsErrorMessagesTestCase(SimpleTestCase, AssertFormErrorsMixin):
def as_divs(self):
if not self:
- return ''
- return mark_safe('
%s
' % ''.join('
%s
' % e for e in self))
+ return ""
+ return mark_safe(
+ '
%s
'
+ % "".join("
%s
" % e for e in self)
+ )
# This form should print errors the default way.
- form1 = TestForm({'first_name': 'John'})
+ form1 = TestForm({"first_name": "John"})
self.assertHTMLEqual(
- str(form1['last_name'].errors),
- '
',
)
# This one should wrap error groups in the customized way.
- form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList)
- self.assertHTMLEqual(str(form2['last_name'].errors), '
',
+ )
def test_error_messages_escaping(self):
# The forms layer doesn't escape input values directly because error
# messages might be presented in non-HTML contexts. Instead, the
# message is marked for escaping by the template engine, so a template
# is needed to trigger the escaping.
- t = Template('{{ form.errors }}')
+ t = Template("{{ form.errors }}")
class SomeForm(Form):
- field = ChoiceField(choices=[('one', 'One')])
+ field = ChoiceField(choices=[("one", "One")])
- f = SomeForm({'field': '",
+ "special_safe_name": "Do not escape",
+ },
+ auto_id=False,
)
- f = EscapingForm({
- 'special_name': "Should escape < & > and ",
- 'special_safe_name': "Do not escape"
- }, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"""
"""
+""",
)
def test_validating_multiple_fields(self):
@@ -1105,25 +1293,36 @@ value="Should escape < & > and <script>alert('xss')<
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']):
- raise ValidationError('Please make sure your passwords match.')
+ 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']
+ return self.cleaned_data["password2"]
f = UserRegistration(auto_id=False)
self.assertEqual(f.errors, {})
f = UserRegistration({}, auto_id=False)
- 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['password2'], ['Please make sure your passwords match.'])
- f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
+ 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["password2"], ["Please make sure your passwords match."]
+ )
+ f = UserRegistration(
+ {"username": "adrian", "password1": "foo", "password2": "foo"},
+ auto_id=False,
+ )
self.assertEqual(f.errors, {})
- self.assertEqual(f.cleaned_data['username'], 'adrian')
- self.assertEqual(f.cleaned_data['password1'], 'foo')
- self.assertEqual(f.cleaned_data['password2'], 'foo')
+ self.assertEqual(f.cleaned_data["username"], "adrian")
+ self.assertEqual(f.cleaned_data["password1"], "foo")
+ self.assertEqual(f.cleaned_data["password2"], "foo")
# Another way of doing multiple-field validation is by implementing the
# Form's clean() method. Usually ValidationError raised by that method
@@ -1144,26 +1343,29 @@ value="Should escape < & > and <script>alert('xss')<
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']):
- raise ValidationError('Please make sure your passwords match.')
+ 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.
errors = {}
- if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE':
- errors['password1'] = 'Forbidden value.'
- if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE':
- errors['password2'] = ['Forbidden value.']
+ if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE":
+ errors["password1"] = "Forbidden value."
+ if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE":
+ errors["password2"] = ["Forbidden value."]
if errors:
raise ValidationError(errors)
# Test Form.add_error()
- if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE2':
- self.add_error(None, 'Non-field error 1.')
- self.add_error('password1', 'Forbidden value 2.')
- if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE2':
- self.add_error('password2', 'Forbidden value 2.')
- raise ValidationError('Non-field error 2.')
+ if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE2":
+ self.add_error(None, "Non-field error 1.")
+ self.add_error("password1", "Forbidden value 2.")
+ if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE2":
+ self.add_error("password2", "Forbidden value 2.")
+ raise ValidationError("Non-field error 2.")
return self.cleaned_data
@@ -1179,21 +1381,26 @@ value="Should escape < & > and <script>alert('xss')<
Password1:
This field is required.
Password2:
This field is required.
-
"""
+""",
)
- 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.'])
+ 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.'])
+ 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(),
"""
""",
)
# Instances of a dynamic Form do not persist fields from one Form instance to
@@ -1373,19 +1597,19 @@ value="Should escape < & > and <script>alert('xss')<
for field in field_list:
self.fields[field[0]] = field[1]
- field_list = [('field1', CharField()), ('field2', CharField())]
+ field_list = [("field1", CharField()), ("field2", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""
""",
)
# Similarly, changes to field attributes do not persist from one Form instance
@@ -1427,24 +1651,42 @@ value="Should escape < & > and <script>alert('xss')<
super().__init__(*args, **kwargs)
if names_required:
- self.fields['first_name'].required = True
- self.fields['first_name'].widget.attrs['class'] = 'required'
- self.fields['last_name'].required = True
- self.fields['last_name'].widget.attrs['class'] = 'required'
+ self.fields["first_name"].required = True
+ self.fields["first_name"].widget.attrs["class"] = "required"
+ self.fields["last_name"].required = True
+ self.fields["last_name"].widget.attrs["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, ({}, {}))
+ 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,
+ ({}, {}),
+ )
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': 'reuired'}, {'class': 'required'})
+ 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": "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, ({}, {}))
+ 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,
+ ({}, {}),
+ )
class Person(Form):
first_name = CharField(max_length=30)
@@ -1454,49 +1696,61 @@ value="Should escape < & > and <script>alert('xss')<
super().__init__(*args, **kwargs)
if name_max_length:
- self.fields['first_name'].max_length = name_max_length
- self.fields['last_name'].max_length = name_max_length
+ self.fields["first_name"].max_length = name_max_length
+ self.fields["last_name"].max_length = name_max_length
f = Person(name_max_length=None)
- self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
+ self.assertEqual(
+ f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30)
+ )
f = Person(name_max_length=20)
- self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20))
+ self.assertEqual(
+ f["first_name"].field.max_length, f["last_name"].field.max_length, (20, 20)
+ )
f = Person(name_max_length=None)
- self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
+ self.assertEqual(
+ f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30)
+ )
# Similarly, choices do not persist from one Form instance to the next.
# Refs #15127.
class Person(Form):
first_name = CharField(required=False)
last_name = CharField(required=False)
- gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male')))
+ gender = ChoiceField(choices=(("f", "Female"), ("m", "Male")))
def __init__(self, allow_unspec_gender=False, *args, **kwargs):
super().__init__(*args, **kwargs)
if allow_unspec_gender:
- self.fields['gender'].choices += (('u', 'Unspecified'),)
+ self.fields["gender"].choices += (("u", "Unspecified"),)
f = Person()
- self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
+ self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")])
f = Person(allow_unspec_gender=True)
- self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male'), ('u', 'Unspecified')])
+ self.assertEqual(
+ f["gender"].field.choices,
+ [("f", "Female"), ("m", "Male"), ("u", "Unspecified")],
+ )
f = Person()
- self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
+ self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")])
def test_validators_independence(self):
"""
The list of form field validators can be modified without polluting
other forms.
"""
+
class MyForm(Form):
myfield = CharField(max_length=25)
f1 = MyForm()
f2 = MyForm()
- f1.fields['myfield'].validators[0] = MaxValueValidator(12)
- self.assertNotEqual(f1.fields['myfield'].validators[0], f2.fields['myfield'].validators[0])
+ f1.fields["myfield"].validators[0] = MaxValueValidator(12)
+ self.assertNotEqual(
+ f1.fields["myfield"].validators[0], f2.fields["myfield"].validators[0]
+ )
def test_hidden_widget(self):
# HiddenInput widgets are displayed differently in the as_table(), as_ul())
@@ -1515,22 +1769,23 @@ value="Should escape < & > and <script>alert('xss')<
"""
First name:
Last name:
Birthday:
-
"""
+
""",
)
self.assertHTMLEqual(
p.as_ul(),
"""
First name:
Last name:
-
Birthday:
"""
+
Birthday:
""",
)
self.assertHTMLEqual(
- p.as_p(), """
First name:
+ p.as_p(),
+ """
First name:
Last name:
-
Birthday:
"""
+
Birthday:
""",
)
# With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
- p = Person(auto_id='id_%s')
+ p = Person(auto_id="id_%s")
self.assertHTMLEqual(
p.as_table(),
"""
"""
+""",
)
# 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)
+ p = Person(
+ {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"},
+ auto_id=False,
+ )
self.assertHTMLEqual(
p.as_table(),
"""
"""
+""",
)
# A corner case: It's possible for a form to have only HiddenInputs.
@@ -1599,9 +1857,17 @@ value="Should escape < & > and <script>alert('xss')<
bar = CharField(widget=HiddenInput)
p = TestForm(auto_id=False)
- self.assertHTMLEqual(p.as_table(), '')
- self.assertHTMLEqual(p.as_ul(), '')
- self.assertHTMLEqual(p.as_p(), '')
+ self.assertHTMLEqual(
+ p.as_table(),
+ '',
+ )
+ self.assertHTMLEqual(
+ p.as_ul(),
+ '',
+ )
+ self.assertHTMLEqual(
+ p.as_p(), ''
+ )
def test_field_order(self):
# A Form's fields are displayed in the same order in which they were defined.
@@ -1622,7 +1888,9 @@ value="Should escape < & > and <script>alert('xss')<
field14 = CharField()
p = TestForm(auto_id=False)
- self.assertHTMLEqual(p.as_table(), """
""",
+ )
def test_explicit_field_order(self):
class TestFormParent(Form):
@@ -1644,17 +1913,17 @@ value="Should escape < & > and <script>alert('xss')<
field4 = CharField()
field5 = CharField()
field6 = CharField()
- field_order = ['field6', 'field5', 'field4', 'field2', 'field1']
+ field_order = ["field6", "field5", "field4", "field2", "field1"]
class TestForm(TestFormParent):
field3 = CharField()
- field_order = ['field2', 'field4', 'field3', 'field5', 'field6']
+ field_order = ["field2", "field4", "field3", "field5", "field6"]
class TestFormRemove(TestForm):
field1 = None
class TestFormMissing(TestForm):
- field_order = ['field2', 'field4', 'field3', 'field5', 'field6', 'field1']
+ field_order = ["field2", "field4", "field3", "field5", "field6", "field1"]
field1 = None
class TestFormInit(TestFormParent):
@@ -1674,11 +1943,13 @@ value="Should escape < & > and <script>alert('xss')<
p = TestForm()
self.assertEqual(list(p.fields), TestFormMissing.field_order)
p = TestFormInit()
- order = [*TestForm.field_order, 'field1']
+ order = [*TestForm.field_order, "field1"]
self.assertEqual(list(p.fields), order)
- TestForm.field_order = ['unknown']
+ TestForm.field_order = ["unknown"]
p = TestForm()
- self.assertEqual(list(p.fields), ['field1', 'field2', 'field4', 'field5', 'field6', 'field3'])
+ self.assertEqual(
+ list(p.fields), ["field1", "field2", "field4", "field5", "field6", "field3"]
+ )
def test_form_html_attributes(self):
# Some Field classes have an effect on the HTML attributes of their associated
@@ -1686,10 +1957,12 @@ value="Should escape < & > and <script>alert('xss')<
# either a TextInput or PasswordInput, then the widget's rendered HTML will
# include the "maxlength" attribute.
class UserRegistration(Form):
- username = CharField(max_length=10) # uses TextInput by default
+ username = CharField(max_length=10) # uses TextInput by default
password = CharField(max_length=10, widget=PasswordInput)
- realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
- address = CharField() # no max_length defined here
+ realname = CharField(
+ max_length=10, widget=TextInput
+ ) # redundantly define widget, just to test
+ address = CharField() # no max_length defined here
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
@@ -1697,21 +1970,23 @@ value="Should escape < & > and <script>alert('xss')<
"""
Username:
Password:
Realname:
-
Address:
"""
+
Address:
""",
)
# If you specify a custom "attrs" that includes the "maxlength" attribute,
# the Field's max_length attribute will override whatever "maxlength" you specify
# in "attrs".
class UserRegistration(Form):
- username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20}))
+ username = CharField(
+ max_length=10, widget=TextInput(attrs={"maxlength": 20})
+ )
password = CharField(max_length=10, widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
-
Password:
"""
+
Password:
""",
)
def test_specifying_labels(self):
@@ -1719,26 +1994,26 @@ value="Should escape < & > and <script>alert('xss')<
# class. If you don't specify 'label', Django will use the field name with
# underscores converted to spaces, and the initial letter capitalized.
class UserRegistration(Form):
- username = CharField(max_length=10, label='Your username')
+ username = CharField(max_length=10, label="Your username")
password1 = CharField(widget=PasswordInput)
- password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)')
+ password2 = CharField(widget=PasswordInput, label="Contraseña (de nuevo)")
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
Your username:
Password1:
-
Contraseña (de nuevo):
"""
+
Contraseña (de nuevo):
""",
)
# Labels for as_* methods will only end in a colon if they don't end in other
# punctuation already.
class Questions(Form):
- q1 = CharField(label='The first question')
- q2 = CharField(label='What is your name?')
- q3 = CharField(label='The answer to life is:')
- q4 = CharField(label='Answer this question!')
- q5 = CharField(label='The last question. Period.')
+ q1 = CharField(label="The first question")
+ q2 = CharField(label="What is your name?")
+ q3 = CharField(label="The answer to life is:")
+ q4 = CharField(label="Answer this question!")
+ q5 = CharField(label="The last question. Period.")
self.assertHTMLEqual(
Questions(auto_id=False).as_p(),
@@ -1746,7 +2021,7 @@ value="Should escape < & > and <script>alert('xss')<
""",
)
# If a label is set to the empty string for a field, that field won't get a label.
class UserRegistration(Form):
- username = CharField(max_length=10, label='')
+ username = CharField(max_length=10, label="")
password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
""",
+ )
+ p = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
p.as_ul(),
"""
Password:
-
"""
+""",
)
# If label is None, Django will auto-create the label from the field name. This
@@ -1783,15 +2061,15 @@ value="Should escape < & > and <script>alert('xss')<
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
-
Password:
"""
+
Password:
""",
)
- p = UserRegistration(auto_id='id_%s')
+ p = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
Password:
-
"""
+""",
)
def test_label_suffix(self):
@@ -1801,31 +2079,40 @@ value="Should escape < & > and <script>alert('xss')<
# punctuation symbol: ., !, ? or :. If you specify a different suffix, it will
# be appended regardless of the last character of the label.
class FavoriteForm(Form):
- color = CharField(label='Favorite color?')
- animal = CharField(label='Favorite animal')
- answer = CharField(label='Secret answer', label_suffix=' =')
+ color = CharField(label="Favorite color?")
+ animal = CharField(label="Favorite animal")
+ answer = CharField(label="Secret answer", label_suffix=" =")
f = FavoriteForm(auto_id=False)
- self.assertHTMLEqual(f.as_ul(), """
""",
+ )
- f = FavoriteForm(auto_id=False, label_suffix='\u2192')
+ f = FavoriteForm(auto_id=False, label_suffix="\u2192")
self.assertHTMLEqual(
f.as_ul(),
'
Favorite color?
\n'
'
Favorite animal\u2192
\n'
- '
Secret answer =
'
+ '
Secret answer =
',
)
def test_initial_data(self):
@@ -1835,7 +2122,7 @@ value="Should escape < & > and <script>alert('xss')<
# empty dictionary). Also, the initial value is *not* used if data for a
# particular required field isn't provided.
class UserRegistration(Form):
- username = CharField(max_length=10, initial='django')
+ username = CharField(max_length=10, initial="django")
password = CharField(widget=PasswordInput)
# Here, we're not submitting any data, so the initial value will be displayed.)
@@ -1843,7 +2130,7 @@ value="Should escape < & > and <script>alert('xss')<
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
-
Password:
"""
+
Password:
""",
)
# Here, we're submitting data, so the initial value will *not* be displayed.
@@ -1853,29 +2140,29 @@ value="Should escape < & > and <script>alert('xss')<
"""
This field is required.
Username:
This field is required.
-Password:
"""
+Password: """,
)
- p = UserRegistration({'username': ''}, auto_id=False)
+ p = UserRegistration({"username": ""}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
This field is required.
Username:
This field is required.
-Password:
"""
+Password: """,
)
- p = UserRegistration({'username': 'foo'}, auto_id=False)
+ p = UserRegistration({"username": "foo"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
This field is required.
-Password:
"""
+Password: """,
)
# 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
# validation error rather than using the initial value for 'username'.
- p = UserRegistration({'password': 'secret'})
- self.assertEqual(p.errors['username'], ['This field is required.'])
+ p = UserRegistration({"password": "secret"})
+ self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
def test_dynamic_initial_data(self):
@@ -1889,61 +2176,66 @@ Password: """
password = CharField(widget=PasswordInput)
# Here, we're not submitting any data, so the initial value will be displayed.)
- p = UserRegistration(initial={'username': 'django'}, auto_id=False)
+ p = UserRegistration(initial={"username": "django"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
-
Password:
"""
+
Password:
""",
)
- p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
+ p = UserRegistration(initial={"username": "stephane"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
-
Password:
"""
+
Password:
""",
)
# The 'initial' parameter is meaningless if you pass data.
- p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
+ p = UserRegistration({}, initial={"username": "django"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
"""
+Password: """,
)
# 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
# validation error rather than using the initial value for 'username'.
- p = UserRegistration({'password': 'secret'}, initial={'username': 'django'})
- self.assertEqual(p.errors['username'], ['This field is required.'])
+ p = UserRegistration({"password": "secret"}, initial={"username": "django"})
+ self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
# If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
# then the latter will get precedence.
class UserRegistration(Form):
- username = CharField(max_length=10, initial='django')
+ username = CharField(max_length=10, initial="django")
password = CharField(widget=PasswordInput)
- p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
+ p = UserRegistration(initial={"username": "babik"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
-
Password:
"""
+
Password:
""",
)
def test_callable_initial_data(self):
@@ -1952,23 +2244,28 @@ Password: """
class UserRegistration(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
- options = MultipleChoiceField(choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')])
+ options = MultipleChoiceField(
+ choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")]
+ )
# We need to define functions that get called later.)
def initial_django():
- return 'django'
+ return "django"
def initial_stephane():
- return 'stephane'
+ return "stephane"
def initial_options():
- return ['f', 'b']
+ return ["f", "b"]
def initial_other_options():
- return ['b', 'w']
+ return ["b", "w"]
# 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)
+ p = UserRegistration(
+ initial={"username": initial_django, "options": initial_options},
+ auto_id=False,
+ )
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
@@ -1977,11 +2274,15 @@ Password: """
-"""
+""",
)
# The 'initial' parameter is meaningless if you pass data.
- p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
+ p = UserRegistration(
+ {},
+ initial={"username": initial_django, "options": initial_options},
+ auto_id=False,
+ )
self.assertHTMLEqual(
p.as_ul(),
"""
"""
+""",
)
p = UserRegistration(
- {'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False
+ {"username": "foo", "options": ["f", "b"]},
+ initial={"username": initial_django},
+ auto_id=False,
)
self.assertHTMLEqual(
p.as_ul(),
@@ -2021,14 +2326,17 @@ Password:
-"""
+""",
)
# 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
# validation error rather than using the initial value for 'username'.
- p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options})
- self.assertEqual(p.errors['username'], ['This field is required.'])
+ p = UserRegistration(
+ {"password": "secret"},
+ initial={"username": initial_django, "options": initial_options},
+ )
+ self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
# If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
@@ -2037,7 +2345,7 @@ Password:
username = CharField(max_length=10, initial=initial_django)
password = CharField(widget=PasswordInput)
options = MultipleChoiceField(
- choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')],
+ choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")],
initial=initial_other_options,
)
@@ -2050,9 +2358,12 @@ Password:
-"""
+""",
+ )
+ p = UserRegistration(
+ initial={"username": initial_stephane, "options": initial_options},
+ auto_id=False,
)
- p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
@@ -2061,31 +2372,31 @@ Password:
-"""
+""",
)
def test_get_initial_for_field(self):
now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456)
class PersonForm(Form):
- first_name = CharField(initial='John')
- last_name = CharField(initial='Doe')
+ first_name = CharField(initial="John")
+ last_name = CharField(initial="Doe")
age = IntegerField()
- occupation = CharField(initial=lambda: 'Unknown')
+ occupation = CharField(initial=lambda: "Unknown")
dt_fixed = DateTimeField(initial=now)
dt_callable = DateTimeField(initial=lambda: now)
- form = PersonForm(initial={'first_name': 'Jane'})
+ form = PersonForm(initial={"first_name": "Jane"})
cases = [
- ('age', None),
- ('last_name', 'Doe'),
+ ("age", None),
+ ("last_name", "Doe"),
# Form.initial overrides Field.initial.
- ('first_name', 'Jane'),
+ ("first_name", "Jane"),
# Callables are evaluated.
- ('occupation', 'Unknown'),
+ ("occupation", "Unknown"),
# Microseconds are removed from datetimes.
- ('dt_fixed', datetime.datetime(2006, 10, 25, 14, 30, 45)),
- ('dt_callable', datetime.datetime(2006, 10, 25, 14, 30, 45)),
+ ("dt_fixed", datetime.datetime(2006, 10, 25, 14, 30, 45)),
+ ("dt_callable", datetime.datetime(2006, 10, 25, 14, 30, 45)),
]
for field_name, expected in cases:
with self.subTest(field_name=field_name):
@@ -2095,72 +2406,79 @@ Password:
def test_changed_data(self):
class Person(Form):
- first_name = CharField(initial='Hans')
- last_name = CharField(initial='Greatel')
+ first_name = CharField(initial="Hans")
+ last_name = CharField(initial="Greatel")
birthday = DateField(initial=datetime.date(1974, 8, 16))
- p = Person(data={'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16'})
+ p = Person(
+ data={"first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16"}
+ )
self.assertTrue(p.is_valid())
- self.assertNotIn('first_name', p.changed_data)
- self.assertIn('last_name', p.changed_data)
- self.assertNotIn('birthday', p.changed_data)
+ self.assertNotIn("first_name", p.changed_data)
+ self.assertIn("last_name", p.changed_data)
+ self.assertNotIn("birthday", p.changed_data)
# A field raising ValidationError is always in changed_data
class PedanticField(forms.Field):
def to_python(self, value):
- raise ValidationError('Whatever')
+ raise ValidationError("Whatever")
class Person2(Person):
- pedantic = PedanticField(initial='whatever', show_hidden_initial=True)
-
- p = Person2(data={
- 'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16',
- 'initial-pedantic': 'whatever',
- })
+ pedantic = PedanticField(initial="whatever", show_hidden_initial=True)
+
+ p = Person2(
+ data={
+ "first_name": "Hans",
+ "last_name": "Scrmbl",
+ "birthday": "1974-08-16",
+ "initial-pedantic": "whatever",
+ }
+ )
self.assertFalse(p.is_valid())
- self.assertIn('pedantic', p.changed_data)
+ self.assertIn("pedantic", p.changed_data)
def test_boundfield_values(self):
# It's possible to get to the value which would be used for rendering
# the widget for a field by using the BoundField's value method.
class UserRegistration(Form):
- username = CharField(max_length=10, initial='djangonaut')
+ username = CharField(max_length=10, initial="djangonaut")
password = CharField(widget=PasswordInput)
unbound = UserRegistration()
- bound = UserRegistration({'password': 'foo'})
- self.assertIsNone(bound['username'].value())
- self.assertEqual(unbound['username'].value(), 'djangonaut')
- self.assertEqual(bound['password'].value(), 'foo')
- self.assertIsNone(unbound['password'].value())
+ bound = UserRegistration({"password": "foo"})
+ self.assertIsNone(bound["username"].value())
+ self.assertEqual(unbound["username"].value(), "djangonaut")
+ self.assertEqual(bound["password"].value(), "foo")
+ self.assertIsNone(unbound["password"].value())
def test_boundfield_initial_called_once(self):
"""
Multiple calls to BoundField().value() in an unbound form should return
the same result each time (#24391).
"""
+
class MyForm(Form):
name = CharField(max_length=10, initial=uuid.uuid4)
form = MyForm()
- name = form['name']
+ name = form["name"]
self.assertEqual(name.value(), name.value())
# BoundField is also cached
- self.assertIs(form['name'], name)
+ self.assertIs(form["name"], name)
def test_boundfield_value_disabled_callable_initial(self):
class PersonForm(Form):
- name = CharField(initial=lambda: 'John Doe', disabled=True)
+ name = CharField(initial=lambda: "John Doe", disabled=True)
# Without form data.
form = PersonForm()
- self.assertEqual(form['name'].value(), 'John Doe')
+ self.assertEqual(form["name"].value(), "John Doe")
# With form data. As the field is disabled, the value should not be
# affected by the form data.
form = PersonForm({})
- self.assertEqual(form['name'].value(), 'John Doe')
+ self.assertEqual(form["name"].value(), "John Doe")
def test_custom_boundfield(self):
class CustomField(CharField):
@@ -2171,7 +2489,7 @@ Password:
name = CustomField()
f = SampleForm()
- self.assertEqual(f['name'], (f, 'name'))
+ self.assertEqual(f["name"], (f, "name"))
def test_initial_datetime_values(self):
now = datetime.datetime.now()
@@ -2199,18 +2517,22 @@ Password:
auto_time_only = TimeField(initial=delayed_now_time)
supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput)
hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput)
- hi_without_microsec = DateTimeField(initial=delayed_now, widget=HiddenInputWithoutMicrosec)
- ti_without_microsec = DateTimeField(initial=delayed_now, widget=TextInputWithoutMicrosec)
+ hi_without_microsec = DateTimeField(
+ initial=delayed_now, widget=HiddenInputWithoutMicrosec
+ )
+ ti_without_microsec = DateTimeField(
+ initial=delayed_now, widget=TextInputWithoutMicrosec
+ )
unbound = DateTimeForm()
cases = [
- ('fixed', now_no_ms),
- ('auto_timestamp', now_no_ms),
- ('auto_time_only', now_no_ms.time()),
- ('supports_microseconds', now),
- ('hi_default_microsec', now),
- ('hi_without_microsec', now_no_ms),
- ('ti_without_microsec', now_no_ms),
+ ("fixed", now_no_ms),
+ ("auto_timestamp", now_no_ms),
+ ("auto_time_only", now_no_ms.time()),
+ ("supports_microseconds", now),
+ ("hi_default_microsec", now),
+ ("hi_without_microsec", now_no_ms),
+ ("ti_without_microsec", now_no_ms),
]
for field_name, expected in cases:
with self.subTest(field_name=field_name):
@@ -2229,7 +2551,12 @@ Password:
def now(self):
self.elapsed_seconds += 1
return datetime.datetime(
- 2006, 10, 25, 14, 30, 45 + self.elapsed_seconds,
+ 2006,
+ 10,
+ 25,
+ 14,
+ 30,
+ 45 + self.elapsed_seconds,
microseconds,
)
@@ -2244,12 +2571,16 @@ Password:
removes microseconds.
"""
form = self.get_datetime_form_with_callable_initial(
- disabled=True, microseconds=123456,
+ disabled=True,
+ microseconds=123456,
)
self.assertEqual(form.errors, {})
- self.assertEqual(form.cleaned_data, {
- 'dt': datetime.datetime(2006, 10, 25, 14, 30, 46),
- })
+ self.assertEqual(
+ form.cleaned_data,
+ {
+ "dt": datetime.datetime(2006, 10, 25, 14, 30, 46),
+ },
+ )
def test_datetime_clean_disabled_callable_initial_bound_field(self):
"""
@@ -2258,23 +2589,28 @@ Password:
"""
form = self.get_datetime_form_with_callable_initial(disabled=True)
self.assertEqual(form.errors, {})
- cleaned = form.cleaned_data['dt']
+ cleaned = form.cleaned_data["dt"]
self.assertEqual(cleaned, datetime.datetime(2006, 10, 25, 14, 30, 46))
- bf = form['dt']
+ bf = form["dt"]
self.assertEqual(cleaned, bf.initial)
def test_datetime_changed_data_callable_with_microseconds(self):
class DateTimeForm(forms.Form):
- dt = DateTimeField(initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456), disabled=True)
+ dt = DateTimeField(
+ initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456),
+ disabled=True,
+ )
- form = DateTimeForm({'dt': '2006-10-25 14:30:45'})
+ form = DateTimeForm({"dt": "2006-10-25 14:30:45"})
self.assertEqual(form.changed_data, [])
def test_help_text(self):
# You can specify descriptive text for a field by using the 'help_text' argument)
class UserRegistration(Form):
- username = CharField(max_length=10, help_text='e.g., user@example.com')
- password = CharField(widget=PasswordInput, help_text='Wählen Sie mit Bedacht.')
+ username = CharField(max_length=10, help_text="e.g., user@example.com")
+ password = CharField(
+ widget=PasswordInput, help_text="Wählen Sie mit Bedacht."
+ )
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
@@ -2282,40 +2618,42 @@ Password:
"""
Username:
e.g., user@example.com
Password:
-Wählen Sie mit Bedacht.
"""
+Wählen Sie mit Bedacht.""",
)
self.assertHTMLEqual(
p.as_p(),
"""
Username:
e.g., user@example.com
Password:
-Wählen Sie mit Bedacht.
"""
+Wählen Sie mit Bedacht.""",
)
self.assertHTMLEqual(
p.as_table(),
"""
Username:
e.g., user@example.com
Password:
-Wählen Sie mit Bedacht.
"""
+Wählen Sie mit Bedacht.""",
)
# The help text is displayed whether or not data is provided for the form.
- p = UserRegistration({'username': 'foo'}, auto_id=False)
+ p = UserRegistration({"username": "foo"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
Username:
e.g., user@example.com
This field is required.
Password:
-Wählen Sie mit Bedacht.
"""
+Wählen Sie mit Bedacht.""",
)
# help_text is not displayed for hidden fields. It can be used for documentation
# purposes, though.
class UserRegistration(Form):
- username = CharField(max_length=10, help_text='e.g., user@example.com')
+ username = CharField(max_length=10, help_text="e.g., user@example.com")
password = CharField(widget=PasswordInput)
- next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
+ next = CharField(
+ widget=HiddenInput, initial="/", help_text="Redirect destination"
+ )
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
@@ -2323,16 +2661,17 @@ Password:
"""
Username:
e.g., user@example.com
Password:
-
"""
+""",
)
def test_help_text_html_safe(self):
"""help_text should not be escaped."""
+
class UserRegistration(Form):
- username = CharField(max_length=10, help_text='e.g., user@example.com')
+ username = CharField(max_length=10, help_text="e.g., user@example.com")
password = CharField(
widget=PasswordInput,
- help_text='Help text is escaped.',
+ help_text="Help text is escaped.",
)
p = UserRegistration(auto_id=False)
@@ -2341,24 +2680,24 @@ Password:
'
Username: '
'e.g., user@example.com
'
'
Password: '
- 'Help text is escaped.
'
+ 'Help text is escaped.',
)
self.assertHTMLEqual(
p.as_p(),
'
Username: '
'e.g., user@example.com
'
'
Password: '
- 'Help text is escaped.
'
+ 'Help text is escaped.',
)
self.assertHTMLEqual(
p.as_table(),
- '
""",
)
# Yes, you can subclass multiple forms. The fields are added in the order in
@@ -2403,11 +2742,14 @@ Password:
haircut_type = CharField()
b = Beatle(auto_id=False)
- self.assertHTMLEqual(b.as_ul(), """
Instrument:
+ self.assertHTMLEqual(
+ b.as_ul(),
+ """
Instrument:
First name:
Last name:
Birthday:
-
Haircut type:
""")
+
Haircut type:
""",
+ )
def test_forms_with_prefixes(self):
# Sometimes it's necessary to have multiple forms display on the same HTML page,
@@ -2423,11 +2765,11 @@ Password:
birthday = DateField()
data = {
- 'person1-first_name': 'John',
- 'person1-last_name': 'Lennon',
- 'person1-birthday': '1940-10-9'
+ "person1-first_name": "John",
+ "person1-last_name": "Lennon",
+ "person1-birthday": "1940-10-9",
}
- p = Person(data, prefix='person1')
+ p = Person(data, prefix="person1")
self.assertHTMLEqual(
p.as_ul(),
"""
First name:
@@ -2435,74 +2777,70 @@ Password:
Last name:
Birthday:
-
"""
+""",
)
self.assertHTMLEqual(
- str(p['first_name']),
- ''
+ str(p["first_name"]),
+ '',
)
self.assertHTMLEqual(
- str(p['last_name']),
- ''
+ str(p["last_name"]),
+ '',
)
self.assertHTMLEqual(
- str(p['birthday']),
- ''
+ str(p["birthday"]),
+ '',
)
self.assertEqual(p.errors, {})
self.assertTrue(p.is_valid())
- 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.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))
# Let's try submitting some bad data to make sure form.errors and field.errors
# work as expected.
data = {
- 'person1-first_name': '',
- 'person1-last_name': '',
- 'person1-birthday': ''
+ "person1-first_name": "",
+ "person1-last_name": "",
+ "person1-birthday": "",
}
- p = Person(data, prefix='person1')
- self.assertEqual(p.errors['first_name'], ['This field is required.'])
- self.assertEqual(p.errors['last_name'], ['This field is required.'])
- self.assertEqual(p.errors['birthday'], ['This field is required.'])
- self.assertEqual(p['first_name'].errors, ['This field is required.'])
+ p = Person(data, prefix="person1")
+ self.assertEqual(p.errors["first_name"], ["This field is required."])
+ self.assertEqual(p.errors["last_name"], ["This field is required."])
+ self.assertEqual(p.errors["birthday"], ["This field is required."])
+ self.assertEqual(p["first_name"].errors, ["This field is required."])
# Accessing a nonexistent field.
with self.assertRaises(KeyError):
- p['person1-first_name'].errors
+ p["person1-first_name"].errors
# In this example, the data doesn't have a prefix, but the form requires it, so
# the form doesn't "see" the fields.
- data = {
- 'first_name': 'John',
- 'last_name': 'Lennon',
- 'birthday': '1940-10-9'
- }
- p = Person(data, prefix='person1')
- self.assertEqual(p.errors['first_name'], ['This field is required.'])
- self.assertEqual(p.errors['last_name'], ['This field is required.'])
- self.assertEqual(p.errors['birthday'], ['This field is required.'])
+ data = {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}
+ p = Person(data, prefix="person1")
+ self.assertEqual(p.errors["first_name"], ["This field is required."])
+ self.assertEqual(p.errors["last_name"], ["This field is required."])
+ self.assertEqual(p.errors["birthday"], ["This field is required."])
# With prefixes, a single data dictionary can hold data for multiple instances
# of the same form.
data = {
- 'person1-first_name': 'John',
- 'person1-last_name': 'Lennon',
- 'person1-birthday': '1940-10-9',
- 'person2-first_name': 'Jim',
- 'person2-last_name': 'Morrison',
- 'person2-birthday': '1943-12-8'
+ "person1-first_name": "John",
+ "person1-last_name": "Lennon",
+ "person1-birthday": "1940-10-9",
+ "person2-first_name": "Jim",
+ "person2-last_name": "Morrison",
+ "person2-birthday": "1943-12-8",
}
- p1 = Person(data, prefix='person1')
+ p1 = Person(data, prefix="person1")
self.assertTrue(p1.is_valid())
- self.assertEqual(p1.cleaned_data['first_name'], 'John')
- self.assertEqual(p1.cleaned_data['last_name'], 'Lennon')
- self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9))
- p2 = Person(data, prefix='person2')
+ self.assertEqual(p1.cleaned_data["first_name"], "John")
+ self.assertEqual(p1.cleaned_data["last_name"], "Lennon")
+ self.assertEqual(p1.cleaned_data["birthday"], datetime.date(1940, 10, 9))
+ p2 = Person(data, prefix="person2")
self.assertTrue(p2.is_valid())
- self.assertEqual(p2.cleaned_data['first_name'], 'Jim')
- self.assertEqual(p2.cleaned_data['last_name'], 'Morrison')
- self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8))
+ self.assertEqual(p2.cleaned_data["first_name"], "Jim")
+ self.assertEqual(p2.cleaned_data["last_name"], "Morrison")
+ self.assertEqual(p2.cleaned_data["birthday"], datetime.date(1943, 12, 8))
# By default, forms append a hyphen between the prefix and the field name, but a
# form can alter that behavior by implementing the add_prefix() method. This
@@ -2514,9 +2852,13 @@ Password:
birthday = DateField()
def add_prefix(self, field_name):
- return '%s-prefix-%s' % (self.prefix, field_name) if self.prefix else field_name
+ return (
+ "%s-prefix-%s" % (self.prefix, field_name)
+ if self.prefix
+ else field_name
+ )
- p = Person(prefix='foo')
+ p = Person(prefix="foo")
self.assertHTMLEqual(
p.as_ul(),
"""
First name:
@@ -2524,30 +2866,30 @@ Password:
Last name:
Birthday:
-
"""
+""",
)
data = {
- 'foo-prefix-first_name': 'John',
- 'foo-prefix-last_name': 'Lennon',
- 'foo-prefix-birthday': '1940-10-9'
+ "foo-prefix-first_name": "John",
+ "foo-prefix-last_name": "Lennon",
+ "foo-prefix-birthday": "1940-10-9",
}
- p = Person(data, prefix='foo')
+ p = Person(data, prefix="foo")
self.assertTrue(p.is_valid())
- 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.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))
def test_class_prefix(self):
# Prefix can be also specified at the class level.
class Person(Form):
first_name = CharField()
- prefix = 'foo'
+ prefix = "foo"
p = Person()
- self.assertEqual(p.prefix, 'foo')
+ self.assertEqual(p.prefix, "foo")
- p = Person(prefix='bar')
- self.assertEqual(p.prefix, 'bar')
+ p = Person(prefix="bar")
+ self.assertEqual(p.prefix, "bar")
def test_forms_with_null_boolean(self):
# NullBooleanField is a bit of a special case because its presentation (widget)
@@ -2556,60 +2898,87 @@ Password:
name = CharField()
is_cool = NullBooleanField()
- p = Person({'name': 'Joe'}, auto_id=False)
- self.assertHTMLEqual(str(p['is_cool']), """""",
+ )
def test_forms_with_file_fields(self):
# FileFields are a special case because they take their data from the request.FILES,
@@ -2626,37 +2995,47 @@ Password:
f = FileForm(data={}, files={}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
- '
'
+ '',
)
- f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False)
+ f = FileForm(
+ data={}, files={"file1": "something that is not a file"}, auto_id=False
+ )
self.assertHTMLEqual(
f.as_table(),
- '
File1:
'
+ "
File1:
"
'
No file was submitted. Check the '
- 'encoding type on the form.
'
- '
'
+ "encoding type on the form."
+ '',
)
- f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'some content')}, auto_id=False)
+ f = FileForm(
+ data={},
+ files={"file1": SimpleUploadedFile("name", b"some content")},
+ auto_id=False,
+ )
self.assertHTMLEqual(
f.as_table(),
'
File1:
',
)
self.assertTrue(f.is_valid())
- file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode())
- f = FileForm(data={}, files={'file1': file1}, auto_id=False)
+ file1 = SimpleUploadedFile(
+ "我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode()
+ )
+ f = FileForm(data={}, files={"file1": file1}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'
File1:
',
@@ -2665,7 +3044,7 @@ Password:
# A required file field with initial data should not contain the
# required HTML attribute. The file input is left blank by the user to
# keep the existing, initial value.
- f = FileForm(initial={'file1': 'resume.txt'}, auto_id=False)
+ f = FileForm(initial={"file1": "resume.txt"}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'
',
)
# A required file field with initial data doesn't contain the required
# HTML attribute. The file input is left blank by the user to keep the
# existing, initial value.
- f = FileForm(initial={'file1': 'resume.txt'}, auto_id=False)
+ f = FileForm(initial={"file1": "resume.txt"}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'
File1:
',
@@ -2707,10 +3086,16 @@ Password:
name = CharField()
# First let's show what happens id empty_permitted=False (the default):
- data = {'artist': '', 'song': ''}
+ data = {"artist": "", "song": ""}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
- self.assertEqual(form.errors, {'name': ['This field is required.'], 'artist': ['This field is required.']})
+ self.assertEqual(
+ form.errors,
+ {
+ "name": ["This field is required."],
+ "artist": ["This field is required."],
+ },
+ )
self.assertEqual(form.cleaned_data, {})
# Now let's show what happens when empty_permitted=True and the form is empty.
@@ -2721,16 +3106,16 @@ Password:
# But if we fill in data for one of the fields, the form is no longer empty and
# the whole thing must pass validation.
- data = {'artist': 'The Doors', 'song': ''}
+ data = {"artist": "The Doors", "song": ""}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
- self.assertEqual(form.errors, {'name': ['This field is required.']})
- self.assertEqual(form.cleaned_data, {'artist': 'The Doors'})
+ self.assertEqual(form.errors, {"name": ["This field is required."]})
+ self.assertEqual(form.cleaned_data, {"artist": "The Doors"})
# If a field is not given in the data then None is returned for its data. Lets
# make sure that when checking for empty_permitted that None is treated
# accordingly.
- data = {'artist': None, 'song': ''}
+ data = {"artist": None, "song": ""}
form = SongForm(data, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
@@ -2740,14 +3125,19 @@ Password:
amount = FloatField()
qty = IntegerField()
- data = {'amount': '0.0', 'qty': ''}
- form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True, use_required_attribute=False)
+ data = {"amount": "0.0", "qty": ""}
+ form = PriceForm(
+ data,
+ initial={"amount": 0.0},
+ empty_permitted=True,
+ use_required_attribute=False,
+ )
self.assertTrue(form.is_valid())
def test_empty_permitted_and_use_required_attribute(self):
msg = (
- 'The empty_permitted and use_required_attribute arguments may not '
- 'both be True.'
+ "The empty_permitted and use_required_attribute arguments may not "
+ "both be True."
)
with self.assertRaisesMessage(ValueError, msg):
Person(empty_permitted=True, use_required_attribute=True)
@@ -2759,8 +3149,8 @@ Password:
name = CharField()
form = SongForm()
- self.assertEqual([f.name for f in form.hidden_fields()], ['token'])
- self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name'])
+ self.assertEqual([f.name for f in form.hidden_fields()], ["token"])
+ self.assertEqual([f.name for f in form.visible_fields()], ["artist", "name"])
def test_hidden_initial_gets_id(self):
class MyForm(Form):
@@ -2770,7 +3160,7 @@ Password:
MyForm().as_table(),
'
',
+ "Paul McCartney",
)
def test_templates_with_forms(self):
class UserRegistration(Form):
- username = CharField(max_length=10, help_text=(
- "Good luck picking a username that doesn't already exist."
- ))
+ username = CharField(
+ max_length=10,
+ help_text=("Good luck picking a username that doesn't already exist."),
+ )
password1 = CharField(widget=PasswordInput)
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']
+ 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.')
+ raise ValidationError("Please make sure your passwords match.")
return self.cleaned_data
# There is full flexibility in displaying form fields in a template.
@@ -3800,169 +4258,169 @@ class TemplateTests(SimpleTestCase):
# responsibility of displaying all the errors, including any that might
# not be associated with a particular field.
t = Template(
- ''
+ ""
)
f = UserRegistration(auto_id=False)
self.assertHTMLEqual(
- t.render(Context({'form': f})),
- '",
)
- f = UserRegistration({'username': 'django'}, auto_id=False)
+ f = UserRegistration({"username": "django"}, auto_id=False)
self.assertHTMLEqual(
- t.render(Context({'form': f})),
- '
'
- '
Your username: '
+ t.render(Context({"form": f})),
+ "
"
+ "
Your username: "
''
- '
'
+ "
"
'
This field is required.
'
- 'Password: '
+ "Password: "
'
'
'
This field is required.
'
- '
Password (again): '
+ "
Password (again): "
'
'
''
- '
',
+ "",
)
# Use form.[field].label to output a field's label. 'label' for a field
# can by specified by using the 'label' argument to a Field class. If
# 'label' is not specified, Django will use the field name with
# underscores converted to spaces, and the initial letter capitalized.
t = Template(
- '
",
)
# Use form.[field].label_tag to output a field's label with a
# tag wrapped around it, but *only* if the given field has an "id"
# attribute. Recall from above that passing the "auto_id" argument to a
# Form gives each field an "id" attribute.
t = Template(
- '
',
+ "",
)
- f = UserRegistration(auto_id='id_%s')
+ f = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
- t.render(Context({'form': f})),
- '
'
+ t.render(Context({"form": f})),
+ "
"
'
Username:'
'
'
+ "required>"
'
Password1:'
'
'
'
Password2:'
'
'
''
- '
',
+ "",
)
# Use form.[field].legend_tag to output a field's label with a \n",
)
# Translated error messages
- with translation.override('ru'):
+ with translation.override("ru"):
f = SomeForm({})
self.assertHTMLEqual(
f.as_p(),
'
\n'
+ "Nainen\n",
)
def test_select_translated_text(self):
# Deep copying translated text shouldn't raise an error.
class CopyForm(Form):
- degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),)))
+ degree = IntegerField(widget=Select(choices=((1, gettext_lazy("test")),)))
CopyForm()
diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py
index 7b9da02a0c..3ac28b1b30 100644
--- a/tests/forms_tests/tests/test_input_formats.py
+++ b/tests/forms_tests/tests/test_input_formats.py
@@ -11,7 +11,7 @@ class LocalizedTimeTests(SimpleTestCase):
def setUp(self):
# nl/formats.py has customized TIME_INPUT_FORMATS:
# ['%H:%M:%S', '%H.%M:%S', '%H.%M', '%H:%M']
- activate('nl')
+ activate("nl")
def tearDown(self):
deactivate()
@@ -21,18 +21,18 @@ class LocalizedTimeTests(SimpleTestCase):
f = forms.TimeField()
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM')
+ f.clean("1:30:05 PM")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13:30:05')
+ result = f.clean("13:30:05")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip
text = f.widget.format_value(result)
- self.assertEqual(text, '13:30:05')
+ self.assertEqual(text, "13:30:05")
# Parse a time in a valid, but non-default format, get a parsed result
- result = f.clean('13:30')
+ result = f.clean("13:30")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -40,7 +40,7 @@ class LocalizedTimeTests(SimpleTestCase):
self.assertEqual(text, "13:30:00")
# ISO formats are accepted, even if not specified in formats.py
- result = f.clean('13:30:05.000155')
+ result = f.clean("13:30:05.000155")
self.assertEqual(result, time(13, 30, 5, 155))
def test_localized_timeField(self):
@@ -48,18 +48,18 @@ class LocalizedTimeTests(SimpleTestCase):
f = forms.TimeField(localize=True)
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM')
+ f.clean("1:30:05 PM")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13:30:05')
+ result = f.clean("13:30:05")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
text = f.widget.format_value(result)
- self.assertEqual(text, '13:30:05')
+ self.assertEqual(text, "13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13:30')
+ result = f.clean("13:30")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -71,12 +71,12 @@ class LocalizedTimeTests(SimpleTestCase):
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM')
+ f.clean("1:30:05 PM")
with self.assertRaises(ValidationError):
- f.clean('13:30:05')
+ f.clean("13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13.30.05')
+ result = f.clean("13.30.05")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
@@ -84,7 +84,7 @@ class LocalizedTimeTests(SimpleTestCase):
self.assertEqual(text, "13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13.30')
+ result = f.clean("13.30")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -96,12 +96,12 @@ class LocalizedTimeTests(SimpleTestCase):
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM')
+ f.clean("1:30:05 PM")
with self.assertRaises(ValidationError):
- f.clean('13:30:05')
+ f.clean("13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13.30.05')
+ result = f.clean("13.30.05")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
@@ -109,7 +109,7 @@ class LocalizedTimeTests(SimpleTestCase):
self.assertEqual(text, "13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13.30')
+ result = f.clean("13.30")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -125,18 +125,18 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
f = forms.TimeField()
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('13:30:05')
+ f.clean("13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('1:30:05 PM')
+ result = f.clean("1:30:05 PM")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip
text = f.widget.format_value(result)
- self.assertEqual(text, '01:30:05 PM')
+ self.assertEqual(text, "01:30:05 PM")
# Parse a time in a valid, but non-default format, get a parsed result
- result = f.clean('1:30 PM')
+ result = f.clean("1:30 PM")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -148,18 +148,18 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
f = forms.TimeField(localize=True)
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('13:30:05')
+ f.clean("13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('1:30:05 PM')
+ result = f.clean("1:30:05 PM")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
text = f.widget.format_value(result)
- self.assertEqual(text, '01:30:05 PM')
+ self.assertEqual(text, "01:30:05 PM")
# Parse a time in a valid format, get a parsed result
- result = f.clean('01:30 PM')
+ result = f.clean("01:30 PM")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -171,12 +171,12 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM')
+ f.clean("1:30:05 PM")
with self.assertRaises(ValidationError):
- f.clean('13:30:05')
+ f.clean("13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13.30.05')
+ result = f.clean("13.30.05")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
@@ -184,7 +184,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:05 PM")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13.30')
+ result = f.clean("13.30")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -196,12 +196,12 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM')
+ f.clean("1:30:05 PM")
with self.assertRaises(ValidationError):
- f.clean('13:30:05')
+ f.clean("13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13.30.05')
+ result = f.clean("13.30.05")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
@@ -209,7 +209,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:05 PM")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13.30')
+ result = f.clean("13.30")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -223,10 +223,10 @@ class SimpleTimeFormatTests(SimpleTestCase):
f = forms.TimeField()
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM')
+ f.clean("1:30:05 PM")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13:30:05')
+ result = f.clean("13:30:05")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
@@ -234,7 +234,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "13:30:05")
# Parse a time in a valid, but non-default format, get a parsed result
- result = f.clean('13:30')
+ result = f.clean("13:30")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -246,10 +246,10 @@ class SimpleTimeFormatTests(SimpleTestCase):
f = forms.TimeField()
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM')
+ f.clean("1:30:05 PM")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13:30:05')
+ result = f.clean("13:30:05")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
@@ -257,7 +257,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('13:30')
+ result = f.clean("13:30")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -269,10 +269,10 @@ class SimpleTimeFormatTests(SimpleTestCase):
f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"])
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('13:30:05')
+ f.clean("13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('1:30:05 PM')
+ result = f.clean("1:30:05 PM")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
@@ -280,7 +280,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('1:30 PM')
+ result = f.clean("1:30 PM")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -292,10 +292,10 @@ class SimpleTimeFormatTests(SimpleTestCase):
f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True)
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('13:30:05')
+ f.clean("13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('1:30:05 PM')
+ result = f.clean("1:30:05 PM")
self.assertEqual(result, time(13, 30, 5))
# The parsed result does a round trip to the same format
@@ -303,7 +303,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "13:30:05")
# Parse a time in a valid format, get a parsed result
- result = f.clean('1:30 PM')
+ result = f.clean("1:30 PM")
self.assertEqual(result, time(13, 30, 0))
# The parsed result does a round trip to default format
@@ -313,7 +313,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
class LocalizedDateTests(SimpleTestCase):
def setUp(self):
- activate('de')
+ activate("de")
def tearDown(self):
deactivate()
@@ -323,21 +323,21 @@ class LocalizedDateTests(SimpleTestCase):
f = forms.DateField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('21/12/2010')
+ f.clean("21/12/2010")
# ISO formats are accepted, even if not specified in formats.py
- self.assertEqual(f.clean('2010-12-21'), date(2010, 12, 21))
+ self.assertEqual(f.clean("2010-12-21"), date(2010, 12, 21))
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.2010')
+ result = f.clean("21.12.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip
text = f.widget.format_value(result)
- self.assertEqual(text, '21.12.2010')
+ self.assertEqual(text, "21.12.2010")
# Parse a date in a valid, but non-default format, get a parsed result
- result = f.clean('21.12.10')
+ result = f.clean("21.12.10")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -349,18 +349,18 @@ class LocalizedDateTests(SimpleTestCase):
f = forms.DateField(localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('21/12/2010')
+ f.clean("21/12/2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.2010')
+ result = f.clean("21.12.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
text = f.widget.format_value(result)
- self.assertEqual(text, '21.12.2010')
+ self.assertEqual(text, "21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.10')
+ result = f.clean("21.12.10")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -372,14 +372,14 @@ class LocalizedDateTests(SimpleTestCase):
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010-12-21')
+ f.clean("2010-12-21")
with self.assertRaises(ValidationError):
- f.clean('21/12/2010')
+ f.clean("21/12/2010")
with self.assertRaises(ValidationError):
- f.clean('21.12.2010')
+ f.clean("21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12.21.2010')
+ result = f.clean("12.21.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
@@ -387,7 +387,7 @@ class LocalizedDateTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12-21-2010')
+ result = f.clean("12-21-2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -399,14 +399,14 @@ class LocalizedDateTests(SimpleTestCase):
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010-12-21')
+ f.clean("2010-12-21")
with self.assertRaises(ValidationError):
- f.clean('21/12/2010')
+ f.clean("21/12/2010")
with self.assertRaises(ValidationError):
- f.clean('21.12.2010')
+ f.clean("21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12.21.2010')
+ result = f.clean("12.21.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
@@ -414,7 +414,7 @@ class LocalizedDateTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12-21-2010')
+ result = f.clean("12-21-2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -430,18 +430,18 @@ class CustomDateInputFormatsTests(SimpleTestCase):
f = forms.DateField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010-12-21')
+ f.clean("2010-12-21")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.2010')
+ result = f.clean("21.12.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip
text = f.widget.format_value(result)
- self.assertEqual(text, '21.12.2010')
+ self.assertEqual(text, "21.12.2010")
# Parse a date in a valid, but non-default format, get a parsed result
- result = f.clean('21-12-2010')
+ result = f.clean("21-12-2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -453,18 +453,18 @@ class CustomDateInputFormatsTests(SimpleTestCase):
f = forms.DateField(localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010-12-21')
+ f.clean("2010-12-21")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.2010')
+ result = f.clean("21.12.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
text = f.widget.format_value(result)
- self.assertEqual(text, '21.12.2010')
+ self.assertEqual(text, "21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21-12-2010')
+ result = f.clean("21-12-2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -476,12 +476,12 @@ class CustomDateInputFormatsTests(SimpleTestCase):
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('21.12.2010')
+ f.clean("21.12.2010")
with self.assertRaises(ValidationError):
- f.clean('2010-12-21')
+ f.clean("2010-12-21")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12.21.2010')
+ result = f.clean("12.21.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
@@ -489,7 +489,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12-21-2010')
+ result = f.clean("12-21-2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -501,12 +501,12 @@ class CustomDateInputFormatsTests(SimpleTestCase):
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('21.12.2010')
+ f.clean("21.12.2010")
with self.assertRaises(ValidationError):
- f.clean('2010-12-21')
+ f.clean("2010-12-21")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12.21.2010')
+ result = f.clean("12.21.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
@@ -514,7 +514,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12-21-2010')
+ result = f.clean("12-21-2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -528,10 +528,10 @@ class SimpleDateFormatTests(SimpleTestCase):
f = forms.DateField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('21.12.2010')
+ f.clean("21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('2010-12-21')
+ result = f.clean("2010-12-21")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
@@ -539,7 +539,7 @@ class SimpleDateFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21")
# Parse a date in a valid, but non-default format, get a parsed result
- result = f.clean('12/21/2010')
+ result = f.clean("12/21/2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -551,10 +551,10 @@ class SimpleDateFormatTests(SimpleTestCase):
f = forms.DateField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('21.12.2010')
+ f.clean("21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('2010-12-21')
+ result = f.clean("2010-12-21")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
@@ -562,7 +562,7 @@ class SimpleDateFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12/21/2010')
+ result = f.clean("12/21/2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -574,10 +574,10 @@ class SimpleDateFormatTests(SimpleTestCase):
f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"])
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010-12-21')
+ f.clean("2010-12-21")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.2010')
+ result = f.clean("21.12.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
@@ -585,7 +585,7 @@ class SimpleDateFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21-12-2010')
+ result = f.clean("21-12-2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -597,10 +597,10 @@ class SimpleDateFormatTests(SimpleTestCase):
f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010-12-21')
+ f.clean("2010-12-21")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.2010')
+ result = f.clean("21.12.2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to the same format
@@ -608,7 +608,7 @@ class SimpleDateFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21-12-2010')
+ result = f.clean("21-12-2010")
self.assertEqual(result, date(2010, 12, 21))
# The parsed result does a round trip to default format
@@ -618,7 +618,7 @@ class SimpleDateFormatTests(SimpleTestCase):
class LocalizedDateTimeTests(SimpleTestCase):
def setUp(self):
- activate('de')
+ activate("de")
def tearDown(self):
deactivate()
@@ -628,21 +628,23 @@ class LocalizedDateTimeTests(SimpleTestCase):
f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM 21/12/2010')
+ f.clean("1:30:05 PM 21/12/2010")
# ISO formats are accepted, even if not specified in formats.py
- self.assertEqual(f.clean('2010-12-21 13:30:05'), datetime(2010, 12, 21, 13, 30, 5))
+ self.assertEqual(
+ f.clean("2010-12-21 13:30:05"), datetime(2010, 12, 21, 13, 30, 5)
+ )
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.2010 13:30:05')
+ result = f.clean("21.12.2010 13:30:05")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip
text = f.widget.format_value(result)
- self.assertEqual(text, '21.12.2010 13:30:05')
+ self.assertEqual(text, "21.12.2010 13:30:05")
# Parse a date in a valid, but non-default format, get a parsed result
- result = f.clean('21.12.2010 13:30')
+ result = f.clean("21.12.2010 13:30")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
@@ -654,18 +656,18 @@ class LocalizedDateTimeTests(SimpleTestCase):
f = forms.DateTimeField(localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM 21/12/2010')
+ f.clean("1:30:05 PM 21/12/2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.2010 13:30:05')
+ result = f.clean("21.12.2010 13:30:05")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to the same format
text = f.widget.format_value(result)
- self.assertEqual(text, '21.12.2010 13:30:05')
+ self.assertEqual(text, "21.12.2010 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('21.12.2010 13:30')
+ result = f.clean("21.12.2010 13:30")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
@@ -677,14 +679,14 @@ class LocalizedDateTimeTests(SimpleTestCase):
f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"])
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010-12-21 13:30:05 13:30:05')
+ f.clean("2010-12-21 13:30:05 13:30:05")
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM 21/12/2010')
+ f.clean("1:30:05 PM 21/12/2010")
with self.assertRaises(ValidationError):
- f.clean('13:30:05 21.12.2010')
+ f.clean("13:30:05 21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('13.30.05 12.21.2010')
+ result = f.clean("13.30.05 12.21.2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to the same format
@@ -692,7 +694,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('13.30 12-21-2010')
+ result = f.clean("13.30 12-21-2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
@@ -701,21 +703,23 @@ class LocalizedDateTimeTests(SimpleTestCase):
def test_localized_dateTimeField_with_inputformat(self):
"Localized DateTimeFields with manually specified input formats can accept those formats"
- f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True)
+ f = forms.DateTimeField(
+ input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True
+ )
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010/12/21 13:30:05')
+ f.clean("2010/12/21 13:30:05")
with self.assertRaises(ValidationError):
- f.clean('1:30:05 PM 21/12/2010')
+ f.clean("1:30:05 PM 21/12/2010")
with self.assertRaises(ValidationError):
- f.clean('13:30:05 21.12.2010')
+ f.clean("13:30:05 21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('13.30.05 12.21.2010')
+ result = f.clean("13.30.05 12.21.2010")
self.assertEqual(datetime(2010, 12, 21, 13, 30, 5), result)
# ISO format is always valid.
self.assertEqual(
- f.clean('2010-12-21 13:30:05'),
+ f.clean("2010-12-21 13:30:05"),
datetime(2010, 12, 21, 13, 30, 5),
)
# The parsed result does a round trip to the same format
@@ -723,7 +727,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('13.30 12-21-2010')
+ result = f.clean("13.30 12-21-2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
@@ -739,18 +743,18 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010/12/21 13:30:05')
+ f.clean("2010/12/21 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('1:30:05 PM 21/12/2010')
+ result = f.clean("1:30:05 PM 21/12/2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip
text = f.widget.format_value(result)
- self.assertEqual(text, '01:30:05 PM 21/12/2010')
+ self.assertEqual(text, "01:30:05 PM 21/12/2010")
# Parse a date in a valid, but non-default format, get a parsed result
- result = f.clean('1:30 PM 21-12-2010')
+ result = f.clean("1:30 PM 21-12-2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
@@ -762,18 +766,18 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
f = forms.DateTimeField(localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010/12/21 13:30:05')
+ f.clean("2010/12/21 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('1:30:05 PM 21/12/2010')
+ result = f.clean("1:30:05 PM 21/12/2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to the same format
text = f.widget.format_value(result)
- self.assertEqual(text, '01:30:05 PM 21/12/2010')
+ self.assertEqual(text, "01:30:05 PM 21/12/2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('1:30 PM 21-12-2010')
+ result = f.clean("1:30 PM 21-12-2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
@@ -785,12 +789,12 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"])
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('13:30:05 21.12.2010')
+ f.clean("13:30:05 21.12.2010")
with self.assertRaises(ValidationError):
- f.clean('2010/12/21 13:30:05')
+ f.clean("2010/12/21 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12.21.2010 13:30:05')
+ result = f.clean("12.21.2010 13:30:05")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to the same format
@@ -798,7 +802,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:05 PM 21/12/2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12-21-2010 13:30')
+ result = f.clean("12-21-2010 13:30")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
@@ -807,15 +811,17 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
def test_localized_dateTimeField_with_inputformat(self):
"Localized DateTimeFields with manually specified input formats can accept those formats"
- f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True)
+ f = forms.DateTimeField(
+ input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True
+ )
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('13:30:05 21.12.2010')
+ f.clean("13:30:05 21.12.2010")
with self.assertRaises(ValidationError):
- f.clean('2010/12/21 13:30:05')
+ f.clean("2010/12/21 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12.21.2010 13:30:05')
+ result = f.clean("12.21.2010 13:30:05")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to the same format
@@ -823,7 +829,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:05 PM 21/12/2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12-21-2010 13:30')
+ result = f.clean("12-21-2010 13:30")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
@@ -837,10 +843,10 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('13:30:05 21.12.2010')
+ f.clean("13:30:05 21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('2010-12-21 13:30:05')
+ result = f.clean("2010-12-21 13:30:05")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to the same format
@@ -848,7 +854,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21 13:30:05")
# Parse a date in a valid, but non-default format, get a parsed result
- result = f.clean('12/21/2010 13:30:05')
+ result = f.clean("12/21/2010 13:30:05")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to default format
@@ -860,10 +866,10 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('13:30:05 21.12.2010')
+ f.clean("13:30:05 21.12.2010")
# Parse a date in a valid format, get a parsed result
- result = f.clean('2010-12-21 13:30:05')
+ result = f.clean("2010-12-21 13:30:05")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to the same format
@@ -871,7 +877,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('12/21/2010 13:30:05')
+ result = f.clean("12/21/2010 13:30:05")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to default format
@@ -880,13 +886,15 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
def test_dateTimeField_with_inputformat(self):
"DateTimeFields with manually specified input formats can accept those formats"
- f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"])
+ f = forms.DateTimeField(
+ input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"]
+ )
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010/12/21 13:30:05')
+ f.clean("2010/12/21 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('1:30:05 PM 21.12.2010')
+ result = f.clean("1:30:05 PM 21.12.2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to the same format
@@ -894,7 +902,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('1:30 PM 21-12-2010')
+ result = f.clean("1:30 PM 21-12-2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
@@ -903,13 +911,15 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
def test_localized_dateTimeField_with_inputformat(self):
"Localized DateTimeFields with manually specified input formats can accept those formats"
- f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True)
+ f = forms.DateTimeField(
+ input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True
+ )
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
- f.clean('2010/12/21 13:30:05')
+ f.clean("2010/12/21 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('1:30:05 PM 21.12.2010')
+ result = f.clean("1:30:05 PM 21.12.2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# The parsed result does a round trip to the same format
@@ -917,7 +927,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21 13:30:05")
# Parse a date in a valid format, get a parsed result
- result = f.clean('1:30 PM 21-12-2010')
+ result = f.clean("1:30 PM 21-12-2010")
self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# The parsed result does a round trip to default format
diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py
index d145560d9b..59fd74f4c9 100644
--- a/tests/forms_tests/tests/test_media.py
+++ b/tests/forms_tests/tests/test_media.py
@@ -4,7 +4,7 @@ from django.test import SimpleTestCase, override_settings
@override_settings(
- STATIC_URL='http://media.example.com/static/',
+ STATIC_URL="http://media.example.com/static/",
)
class FormsMediaTestCase(SimpleTestCase):
"""Tests for the media handling on widgets and forms"""
@@ -12,8 +12,12 @@ 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'),
+ 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),
@@ -21,19 +25,21 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
self.assertEqual(
repr(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'])"
+ "js=['/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'])",
)
class Foo:
- 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')
+ 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",
+ )
m3 = Media(Foo)
self.assertEqual(
@@ -42,7 +48,7 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
# A widget can exist without a media definition
@@ -50,7 +56,7 @@ class FormsMediaTestCase(SimpleTestCase):
pass
w = MyWidget()
- self.assertEqual(str(w.media), '')
+ self.assertEqual(str(w.media), "")
def test_media_dsl(self):
###############################################################
@@ -62,10 +68,12 @@ class FormsMediaTestCase(SimpleTestCase):
# with the value of settings.MEDIA_URL
class MyWidget1(TextInput):
class 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')
+ 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",
+ )
w1 = MyWidget1()
self.assertEqual(
@@ -74,21 +82,21 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
# Media objects can be interrogated by media type
self.assertEqual(
- str(w1.media['css']),
+ str(w1.media["css"]),
"""
-"""
+""",
)
self.assertEqual(
- str(w1.media['js']),
+ str(w1.media["js"]),
"""
-"""
+""",
)
def test_combine_media(self):
@@ -96,24 +104,22 @@ class FormsMediaTestCase(SimpleTestCase):
# once. Duplicated media definitions are ignored.
class MyWidget1(TextInput):
class 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')
+ 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",
+ )
class MyWidget2(TextInput):
class Media:
- css = {
- 'all': ('/path/to/css2', '/path/to/css3')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ css = {"all": ("/path/to/css2", "/path/to/css3")}
+ js = ("/path/to/js1", "/path/to/js4")
class MyWidget3(TextInput):
class Media:
- css = {
- 'all': ('path/to/css1', '/path/to/css3')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ css = {"all": ("path/to/css1", "/path/to/css3")}
+ js = ("/path/to/js1", "/path/to/js4")
w1 = MyWidget1()
w2 = MyWidget2()
@@ -126,7 +132,7 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
# media addition hasn't affected the original objects
@@ -136,7 +142,7 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
# Regression check for #12879: specifying the same CSS or JS file
@@ -144,23 +150,29 @@ class FormsMediaTestCase(SimpleTestCase):
# only being included once.
class MyWidget4(TextInput):
class Media:
- css = {'all': ('/path/to/css1', '/path/to/css1')}
- js = ('/path/to/js1', '/path/to/js1')
+ css = {"all": ("/path/to/css1", "/path/to/css1")}
+ js = ("/path/to/js1", "/path/to/js1")
w4 = MyWidget4()
- self.assertEqual(str(w4.media), """
-""")
+ self.assertEqual(
+ str(w4.media),
+ """
+""",
+ )
def test_media_deduplication(self):
# A deduplication test applied directly to a Media object, to confirm
# that the deduplication doesn't only happen at the point of merging
# two or more media objects.
media = Media(
- css={'all': ('/path/to/css1', '/path/to/css1')},
- js=('/path/to/js1', '/path/to/js1'),
+ css={"all": ("/path/to/css1", "/path/to/css1")},
+ js=("/path/to/js1", "/path/to/js1"),
+ )
+ self.assertEqual(
+ str(media),
+ """
+""",
)
- self.assertEqual(str(media), """
-""")
def test_media_property(self):
###############################################################
@@ -170,38 +182,53 @@ class FormsMediaTestCase(SimpleTestCase):
# Widget media can be defined as a property
class MyWidget4(TextInput):
def _media(self):
- return Media(css={'all': ('/some/path',)}, js=('/some/js',))
+ return Media(css={"all": ("/some/path",)}, js=("/some/js",))
+
media = property(_media)
w4 = MyWidget4()
- self.assertEqual(str(w4.media), """
-""")
+ self.assertEqual(
+ str(w4.media),
+ """
+""",
+ )
# Media properties can reference the media of their parents
class MyWidget5(MyWidget4):
def _media(self):
- return super().media + Media(css={'all': ('/other/path',)}, js=('/other/js',))
+ return super().media + Media(
+ css={"all": ("/other/path",)}, js=("/other/js",)
+ )
+
media = property(_media)
w5 = MyWidget5()
- self.assertEqual(str(w5.media), """
+ self.assertEqual(
+ str(w5.media),
+ """
-""")
+""",
+ )
def test_media_property_parent_references(self):
# Media properties can reference the media of their parents,
# even if the parent media was defined using a class
class MyWidget1(TextInput):
class 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')
+ 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",
+ )
class MyWidget6(MyWidget1):
def _media(self):
- return super().media + Media(css={'all': ('/other/path',)}, js=('/other/js',))
+ return super().media + Media(
+ css={"all": ("/other/path",)}, js=("/other/js",)
+ )
+
media = property(_media)
w6 = MyWidget6()
@@ -213,7 +240,7 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
def test_media_inheritance(self):
@@ -224,10 +251,12 @@ class FormsMediaTestCase(SimpleTestCase):
# If a widget extends another but provides no media definition, it inherits the parent widget's media
class MyWidget1(TextInput):
class 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')
+ 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",
+ )
class MyWidget7(MyWidget1):
pass
@@ -239,16 +268,14 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
# If a widget extends another but defines media, it extends the parent widget's media by default
class MyWidget8(MyWidget1):
class Media:
- css = {
- 'all': ('/path/to/css3', 'path/to/css1')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ css = {"all": ("/path/to/css3", "path/to/css1")}
+ js = ("/path/to/js1", "/path/to/js4")
w8 = MyWidget8()
self.assertEqual(
@@ -259,7 +286,7 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
def test_media_inheritance_from_property(self):
@@ -267,22 +294,23 @@ class FormsMediaTestCase(SimpleTestCase):
# even if the parent defined media using a property.
class MyWidget1(TextInput):
class 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')
+ 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",
+ )
class MyWidget4(TextInput):
def _media(self):
- return Media(css={'all': ('/some/path',)}, js=('/some/js',))
+ return Media(css={"all": ("/some/path",)}, js=("/some/js",))
+
media = property(_media)
class MyWidget9(MyWidget4):
class Media:
- css = {
- 'all': ('/other/path',)
- }
- js = ('/other/js',)
+ css = {"all": ("/other/path",)}
+ js = ("/other/js",)
w9 = MyWidget9()
self.assertEqual(
@@ -290,40 +318,41 @@ class FormsMediaTestCase(SimpleTestCase):
"""
-"""
+""",
)
# A widget can disable media inheritance by specifying 'extend=False'
class MyWidget10(MyWidget1):
class Media:
extend = False
- css = {
- 'all': ('/path/to/css3', 'path/to/css1')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ css = {"all": ("/path/to/css3", "path/to/css1")}
+ js = ("/path/to/js1", "/path/to/js4")
w10 = MyWidget10()
- self.assertEqual(str(w10.media), """
+ self.assertEqual(
+ str(w10.media),
+ """
-""")
+""",
+ )
def test_media_inheritance_extends(self):
# A widget can explicitly enable full media inheritance by specifying 'extend=True'
class MyWidget1(TextInput):
class 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')
+ 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",
+ )
class MyWidget11(MyWidget1):
class Media:
extend = True
- css = {
- 'all': ('/path/to/css3', 'path/to/css1')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ css = {"all": ("/path/to/css3", "path/to/css1")}
+ js = ("/path/to/js1", "/path/to/js4")
w11 = MyWidget11()
self.assertEqual(
@@ -334,25 +363,25 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
def test_media_inheritance_single_type(self):
# A widget can enable inheritance of one media type by specifying extend as a tuple
class MyWidget1(TextInput):
class 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')
+ 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",
+ )
class MyWidget12(MyWidget1):
class Media:
- extend = ('css',)
- css = {
- 'all': ('/path/to/css3', 'path/to/css1')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ extend = ("css",)
+ css = {"all": ("/path/to/css3", "path/to/css1")}
+ js = ("/path/to/js1", "/path/to/js4")
w12 = MyWidget12()
self.assertEqual(
@@ -361,7 +390,7 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
def test_multi_media(self):
@@ -373,11 +402,11 @@ class FormsMediaTestCase(SimpleTestCase):
class MultimediaWidget(TextInput):
class Media:
css = {
- 'screen, print': ('/file1', '/file2'),
- 'screen': ('/file3',),
- 'print': ('/file4',)
+ "screen, print": ("/file1", "/file2"),
+ "screen": ("/file3",),
+ "print": ("/file4",),
}
- js = ('/path/to/js1', '/path/to/js4')
+ js = ("/path/to/js1", "/path/to/js4")
multimedia = MultimediaWidget()
self.assertEqual(
@@ -387,7 +416,7 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
def test_multi_widget(self):
@@ -397,24 +426,22 @@ class FormsMediaTestCase(SimpleTestCase):
class MyWidget1(TextInput):
class 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')
+ 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",
+ )
class MyWidget2(TextInput):
class Media:
- css = {
- 'all': ('/path/to/css2', '/path/to/css3')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ css = {"all": ("/path/to/css2", "/path/to/css3")}
+ js = ("/path/to/js1", "/path/to/js4")
class MyWidget3(TextInput):
class Media:
- css = {
- 'all': ('path/to/css1', '/path/to/css3')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ css = {"all": ("path/to/css1", "/path/to/css3")}
+ js = ("/path/to/js1", "/path/to/js4")
# MultiWidgets have a default media definition that gets all the
# media from the component widgets
@@ -432,7 +459,7 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
def test_form_media(self):
@@ -442,29 +469,28 @@ class FormsMediaTestCase(SimpleTestCase):
class MyWidget1(TextInput):
class 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')
+ 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",
+ )
class MyWidget2(TextInput):
class Media:
- css = {
- 'all': ('/path/to/css2', '/path/to/css3')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ css = {"all": ("/path/to/css2", "/path/to/css3")}
+ js = ("/path/to/js1", "/path/to/js4")
class MyWidget3(TextInput):
class Media:
- css = {
- 'all': ('path/to/css1', '/path/to/css3')
- }
- js = ('/path/to/js1', '/path/to/js4')
+ css = {"all": ("path/to/css1", "/path/to/css3")}
+ js = ("/path/to/js1", "/path/to/js4")
# You can ask a form for the media required by its widgets.
class MyForm(Form):
field1 = CharField(max_length=20, widget=MyWidget1())
field2 = CharField(max_length=20, widget=MyWidget2())
+
f1 = MyForm()
self.assertEqual(
str(f1.media),
@@ -474,12 +500,13 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
# 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),
@@ -489,7 +516,7 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
# Forms can also define media, following the same rules as widgets.
@@ -498,10 +525,9 @@ class FormsMediaTestCase(SimpleTestCase):
field2 = CharField(max_length=20, widget=MyWidget2())
class Media:
- js = ('/some/form/javascript',)
- css = {
- 'all': ('/some/form/css',)
- }
+ js = ("/some/form/javascript",)
+ css = {"all": ("/some/form/css",)}
+
f3 = FormWithMedia()
self.assertEqual(
str(f3.media),
@@ -513,12 +539,14 @@ class FormsMediaTestCase(SimpleTestCase):
-"""
+""",
)
# Media works in templates
self.assertEqual(
- Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})),
+ Template("{{ form.media.js }}{{ form.media.css }}").render(
+ Context({"form": f3})
+ ),
"""
@@ -527,12 +555,12 @@ class FormsMediaTestCase(SimpleTestCase):
"""
-"""
+""",
)
def test_html_safe(self):
- media = Media(css={'all': ['/path/to/css']}, js=['/path/to/js'])
- self.assertTrue(hasattr(Media, '__html__'))
+ media = Media(css={"all": ["/path/to/css"]}, js=["/path/to/js"])
+ self.assertTrue(hasattr(Media, "__html__"))
self.assertEqual(str(media), media.__html__())
def test_merge(self):
@@ -544,7 +572,10 @@ class FormsMediaTestCase(SimpleTestCase):
(([1, 2], [1, 3]), [1, 2, 3]),
(([1, 2], [3, 2]), [1, 3, 2]),
(([1, 2], [1, 2]), [1, 2]),
- ([[1, 2], [1, 3], [2, 3], [5, 7], [5, 6], [6, 7, 9], [8, 9]], [1, 5, 8, 2, 6, 3, 7, 9]),
+ (
+ [[1, 2], [1, 3], [2, 3], [5, 7], [5, 6], [6, 7, 9], [8, 9]],
+ [1, 5, 8, 2, 6, 3, 7, 9],
+ ),
((), []),
(([1, 2],), [1, 2]),
)
@@ -553,7 +584,7 @@ class FormsMediaTestCase(SimpleTestCase):
self.assertEqual(Media.merge(*lists), expected)
def test_merge_warning(self):
- msg = 'Detected duplicate Media files in an opposite order: [1, 2], [2, 1]'
+ msg = "Detected duplicate Media files in an opposite order: [1, 2], [2, 1]"
with self.assertWarnsMessage(RuntimeWarning, msg):
self.assertEqual(Media.merge([1, 2], [2, 1]), [1, 2])
@@ -561,51 +592,60 @@ class FormsMediaTestCase(SimpleTestCase):
"""
The relative order of scripts is preserved in a three-way merge.
"""
- widget1 = Media(js=['color-picker.js'])
- widget2 = Media(js=['text-editor.js'])
- widget3 = Media(js=['text-editor.js', 'text-editor-extras.js', 'color-picker.js'])
+ widget1 = Media(js=["color-picker.js"])
+ widget2 = Media(js=["text-editor.js"])
+ widget3 = Media(
+ js=["text-editor.js", "text-editor-extras.js", "color-picker.js"]
+ )
merged = widget1 + widget2 + widget3
- self.assertEqual(merged._js, ['text-editor.js', 'text-editor-extras.js', 'color-picker.js'])
+ self.assertEqual(
+ merged._js, ["text-editor.js", "text-editor-extras.js", "color-picker.js"]
+ )
def test_merge_js_three_way2(self):
# The merge prefers to place 'c' before 'b' and 'g' before 'h' to
# preserve the original order. The preference 'c'->'b' is overridden by
# widget3's media, but 'g'->'h' survives in the final ordering.
- widget1 = Media(js=['a', 'c', 'f', 'g', 'k'])
- widget2 = Media(js=['a', 'b', 'f', 'h', 'k'])
- widget3 = Media(js=['b', 'c', 'f', 'k'])
+ widget1 = Media(js=["a", "c", "f", "g", "k"])
+ widget2 = Media(js=["a", "b", "f", "h", "k"])
+ widget3 = Media(js=["b", "c", "f", "k"])
merged = widget1 + widget2 + widget3
- self.assertEqual(merged._js, ['a', 'b', 'c', 'f', 'g', 'h', 'k'])
+ self.assertEqual(merged._js, ["a", "b", "c", "f", "g", "h", "k"])
def test_merge_css_three_way(self):
- widget1 = Media(css={'screen': ['c.css'], 'all': ['d.css', 'e.css']})
- widget2 = Media(css={'screen': ['a.css']})
- widget3 = Media(css={'screen': ['a.css', 'b.css', 'c.css'], 'all': ['e.css']})
- widget4 = Media(css={'all': ['d.css', 'e.css'], 'screen': ['c.css']})
+ widget1 = Media(css={"screen": ["c.css"], "all": ["d.css", "e.css"]})
+ widget2 = Media(css={"screen": ["a.css"]})
+ widget3 = Media(css={"screen": ["a.css", "b.css", "c.css"], "all": ["e.css"]})
+ widget4 = Media(css={"all": ["d.css", "e.css"], "screen": ["c.css"]})
merged = widget1 + widget2
# c.css comes before a.css because widget1 + widget2 establishes this
# order.
- self.assertEqual(merged._css, {'screen': ['c.css', 'a.css'], 'all': ['d.css', 'e.css']})
+ self.assertEqual(
+ merged._css, {"screen": ["c.css", "a.css"], "all": ["d.css", "e.css"]}
+ )
merged = merged + widget3
# widget3 contains an explicit ordering of c.css and a.css.
- self.assertEqual(merged._css, {'screen': ['a.css', 'b.css', 'c.css'], 'all': ['d.css', 'e.css']})
+ self.assertEqual(
+ merged._css,
+ {"screen": ["a.css", "b.css", "c.css"], "all": ["d.css", "e.css"]},
+ )
# Media ordering does not matter.
merged = widget1 + widget4
- self.assertEqual(merged._css, {'screen': ['c.css'], 'all': ['d.css', 'e.css']})
+ self.assertEqual(merged._css, {"screen": ["c.css"], "all": ["d.css", "e.css"]})
def test_add_js_deduplication(self):
- widget1 = Media(js=['a', 'b', 'c'])
- widget2 = Media(js=['a', 'b'])
- widget3 = Media(js=['a', 'c', 'b'])
+ widget1 = Media(js=["a", "b", "c"])
+ widget2 = Media(js=["a", "b"])
+ widget3 = Media(js=["a", "c", "b"])
merged = widget1 + widget1
- self.assertEqual(merged._js_lists, [['a', 'b', 'c']])
- self.assertEqual(merged._js, ['a', 'b', 'c'])
+ self.assertEqual(merged._js_lists, [["a", "b", "c"]])
+ self.assertEqual(merged._js, ["a", "b", "c"])
merged = widget1 + widget2
- self.assertEqual(merged._js_lists, [['a', 'b', 'c'], ['a', 'b']])
- self.assertEqual(merged._js, ['a', 'b', 'c'])
+ self.assertEqual(merged._js_lists, [["a", "b", "c"], ["a", "b"]])
+ self.assertEqual(merged._js, ["a", "b", "c"])
# Lists with items in a different order are preserved when added.
merged = widget1 + widget3
- self.assertEqual(merged._js_lists, [['a', 'b', 'c'], ['a', 'c', 'b']])
+ self.assertEqual(merged._js_lists, [["a", "b", "c"], ["a", "c", "b"]])
msg = (
"Detected duplicate Media files in an opposite order: "
"['a', 'b', 'c'], ['a', 'c', 'b']"
@@ -614,25 +654,31 @@ class FormsMediaTestCase(SimpleTestCase):
merged._js
def test_add_css_deduplication(self):
- widget1 = Media(css={'screen': ['a.css'], 'all': ['b.css']})
- widget2 = Media(css={'screen': ['c.css']})
- widget3 = Media(css={'screen': ['a.css'], 'all': ['b.css', 'c.css']})
- widget4 = Media(css={'screen': ['a.css'], 'all': ['c.css', 'b.css']})
+ widget1 = Media(css={"screen": ["a.css"], "all": ["b.css"]})
+ widget2 = Media(css={"screen": ["c.css"]})
+ widget3 = Media(css={"screen": ["a.css"], "all": ["b.css", "c.css"]})
+ widget4 = Media(css={"screen": ["a.css"], "all": ["c.css", "b.css"]})
merged = widget1 + widget1
- self.assertEqual(merged._css_lists, [{'screen': ['a.css'], 'all': ['b.css']}])
- self.assertEqual(merged._css, {'screen': ['a.css'], 'all': ['b.css']})
+ self.assertEqual(merged._css_lists, [{"screen": ["a.css"], "all": ["b.css"]}])
+ self.assertEqual(merged._css, {"screen": ["a.css"], "all": ["b.css"]})
merged = widget1 + widget2
- self.assertEqual(merged._css_lists, [
- {'screen': ['a.css'], 'all': ['b.css']},
- {'screen': ['c.css']},
- ])
- self.assertEqual(merged._css, {'screen': ['a.css', 'c.css'], 'all': ['b.css']})
+ self.assertEqual(
+ merged._css_lists,
+ [
+ {"screen": ["a.css"], "all": ["b.css"]},
+ {"screen": ["c.css"]},
+ ],
+ )
+ self.assertEqual(merged._css, {"screen": ["a.css", "c.css"], "all": ["b.css"]})
merged = widget3 + widget4
# Ordering within lists is preserved.
- self.assertEqual(merged._css_lists, [
- {'screen': ['a.css'], 'all': ['b.css', 'c.css']},
- {'screen': ['a.css'], 'all': ['c.css', 'b.css']}
- ])
+ self.assertEqual(
+ merged._css_lists,
+ [
+ {"screen": ["a.css"], "all": ["b.css", "c.css"]},
+ {"screen": ["a.css"], "all": ["c.css", "b.css"]},
+ ],
+ )
msg = (
"Detected duplicate Media files in an opposite order: "
"['b.css', 'c.css'], ['c.css', 'b.css']"
@@ -641,8 +687,8 @@ class FormsMediaTestCase(SimpleTestCase):
merged._css
def test_add_empty(self):
- media = Media(css={'screen': ['a.css']}, js=['a'])
+ media = Media(css={"screen": ["a.css"]}, js=["a"])
empty_media = Media()
merged = media + empty_media
- self.assertEqual(merged._css_lists, [{'screen': ['a.css']}])
- self.assertEqual(merged._js_lists, [['a']])
+ self.assertEqual(merged._css_lists, [{"screen": ["a.css"]}])
+ self.assertEqual(merged._js_lists, [["a"]])
diff --git a/tests/forms_tests/tests/test_renderers.py b/tests/forms_tests/tests/test_renderers.py
index 47452fa489..3e973ad8fc 100644
--- a/tests/forms_tests/tests/test_renderers.py
+++ b/tests/forms_tests/tests/test_renderers.py
@@ -2,7 +2,10 @@ import os
import unittest
from django.forms.renderers import (
- BaseRenderer, DjangoTemplates, Jinja2, TemplatesSetting,
+ BaseRenderer,
+ DjangoTemplates,
+ Jinja2,
+ TemplatesSetting,
)
from django.test import SimpleTestCase
@@ -13,38 +16,39 @@ except ImportError:
class SharedTests:
- expected_widget_dir = 'templates'
+ expected_widget_dir = "templates"
def test_installed_apps_template_found(self):
"""Can find a custom template in INSTALLED_APPS."""
renderer = self.renderer()
# Found because forms_tests is .
- tpl = renderer.get_template('forms_tests/custom_widget.html')
+ tpl = renderer.get_template("forms_tests/custom_widget.html")
expected_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
- '..',
- self.expected_widget_dir + '/forms_tests/custom_widget.html',
+ "..",
+ self.expected_widget_dir + "/forms_tests/custom_widget.html",
)
)
self.assertEqual(tpl.origin.name, expected_path)
class BaseTemplateRendererTests(SimpleTestCase):
-
def test_get_renderer(self):
- with self.assertRaisesMessage(NotImplementedError, 'subclasses must implement get_template()'):
- BaseRenderer().get_template('')
+ with self.assertRaisesMessage(
+ NotImplementedError, "subclasses must implement get_template()"
+ ):
+ BaseRenderer().get_template("")
class DjangoTemplatesTests(SharedTests, SimpleTestCase):
renderer = DjangoTemplates
-@unittest.skipIf(jinja2 is None, 'jinja2 required')
+@unittest.skipIf(jinja2 is None, "jinja2 required")
class Jinja2Tests(SharedTests, SimpleTestCase):
renderer = Jinja2
- expected_widget_dir = 'jinja2'
+ expected_widget_dir = "jinja2"
class TemplatesSettingTests(SharedTests, SimpleTestCase):
diff --git a/tests/forms_tests/tests/test_utils.py b/tests/forms_tests/tests/test_utils.py
index e0e9a0e22e..c4a2e5c651 100644
--- a/tests/forms_tests/tests/test_utils.py
+++ b/tests/forms_tests/tests/test_utils.py
@@ -16,28 +16,31 @@ class FormsUtilsTestCase(SimpleTestCase):
# flatatt #
###########
- self.assertEqual(flatatt({'id': "header"}), ' id="header"')
- self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"')
+ self.assertEqual(flatatt({"id": "header"}), ' id="header"')
self.assertEqual(
- flatatt({'class': "news", 'title': "Read this", 'required': "required"}),
- ' class="news" required="required" title="Read this"'
+ flatatt({"class": "news", "title": "Read this"}),
+ ' class="news" title="Read this"',
)
self.assertEqual(
- flatatt({'class': "news", 'title': "Read this", 'required': True}),
- ' class="news" title="Read this" required'
+ flatatt({"class": "news", "title": "Read this", "required": "required"}),
+ ' class="news" required="required" title="Read this"',
)
self.assertEqual(
- flatatt({'class': "news", 'title': "Read this", 'required': False}),
- ' class="news" title="Read this"'
+ flatatt({"class": "news", "title": "Read this", "required": True}),
+ ' class="news" title="Read this" required',
)
- self.assertEqual(flatatt({'class': None}), '')
- self.assertEqual(flatatt({}), '')
+ self.assertEqual(
+ flatatt({"class": "news", "title": "Read this", "required": False}),
+ ' class="news" title="Read this"',
+ )
+ self.assertEqual(flatatt({"class": None}), "")
+ self.assertEqual(flatatt({}), "")
def test_flatatt_no_side_effects(self):
"""
flatatt() does not modify the dict passed in.
"""
- attrs = {'foo': 'bar', 'true': True, 'false': False}
+ attrs = {"foo": "bar", "true": True, "false": False}
attrs_copy = copy.copy(attrs)
self.assertEqual(attrs, attrs_copy)
@@ -58,46 +61,62 @@ class FormsUtilsTestCase(SimpleTestCase):
# Can take a string.
self.assertHTMLEqual(
str(ErrorList(ValidationError("There was an error.").messages)),
- '
There was an error.
'
+ '
There was an error.
',
)
# Can take a Unicode string.
self.assertHTMLEqual(
str(ErrorList(ValidationError("Not \u03C0.").messages)),
- '
Not π.
'
+ '
Not π.
',
)
# Can take a lazy string.
self.assertHTMLEqual(
str(ErrorList(ValidationError(gettext_lazy("Error.")).messages)),
- '
Error.
'
+ '
Error.
',
)
# Can take a list.
self.assertHTMLEqual(
str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)),
- '
Error one.
Error two.
'
+ '
Error one.
Error two.
',
)
# Can take a dict.
self.assertHTMLEqual(
- str(ErrorList(sorted(ValidationError({'error_1': "1. Error one.", 'error_2': "2. Error two."}).messages))),
- '
',
)
# Can take a mixture in a list.
self.assertHTMLEqual(
- str(ErrorList(sorted(ValidationError([
- "1. First error.",
- "2. Not \u03C0.",
- gettext_lazy("3. Error."),
- {
- 'error_1': "4. First dict error.",
- 'error_2': "5. Second dict error.",
- },
- ]).messages))),
+ str(
+ ErrorList(
+ sorted(
+ ValidationError(
+ [
+ "1. First error.",
+ "2. Not \u03C0.",
+ gettext_lazy("3. Error."),
+ {
+ "error_1": "4. First dict error.",
+ "error_2": "5. Second dict error.",
+ },
+ ]
+ ).messages
+ )
+ )
+ ),
'
'
- '
1. First error.
'
- '
2. Not π.
'
- '
3. Error.
'
- '
4. First dict error.
'
- '
5. Second dict error.
'
- '
'
+ "
1. First error.
"
+ "
2. Not π.
"
+ "
3. Error.
"
+ "
4. First dict error.
"
+ "
5. Second dict error.
"
+ "",
)
class VeryBadError:
@@ -107,7 +126,7 @@ class FormsUtilsTestCase(SimpleTestCase):
# Can take a non-string.
self.assertHTMLEqual(
str(ErrorList(ValidationError(VeryBadError()).messages)),
- '
A very bad error.
'
+ '
A very bad error.
',
)
# Escapes non-safe input but not input marked safe.
@@ -115,36 +134,38 @@ class FormsUtilsTestCase(SimpleTestCase):
self.assertHTMLEqual(
str(ErrorList([example])),
'
Example of link: '
- '<a href="http://www.example.com/">example</a>
- """)
+ """,
+ )
def test_render_none(self):
"""
If the value is None, none of the options are selected, even if the
choices have an empty option.
"""
- self.check_html(self.widget(choices=(('', 'Unknown'),) + self.beatles), 'beatles', None, html="""
+ self.check_html(
+ self.widget(choices=(("", "Unknown"),) + self.beatles),
+ "beatles",
+ None,
+ html="""
Unknown
John
@@ -43,13 +57,14 @@ class CheckboxSelectMultipleTest(WidgetTest):