summaryrefslogtreecommitdiff
path: root/tests/forms_tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests/forms_tests')
-rw-r--r--tests/forms_tests/field_tests/test_booleanfield.py3
-rw-r--r--tests/forms_tests/field_tests/test_charfield.py3
-rw-r--r--tests/forms_tests/field_tests/test_datefield.py4
-rw-r--r--tests/forms_tests/field_tests/test_filefield.py4
-rw-r--r--tests/forms_tests/field_tests/test_typedchoicefield.py11
-rw-r--r--tests/forms_tests/field_tests/test_typedmultiplechoicefield.py11
-rw-r--r--tests/forms_tests/tests/test_forms.py261
-rw-r--r--tests/forms_tests/tests/test_formsets.py4
-rw-r--r--tests/forms_tests/tests/test_input_formats.py55
-rw-r--r--tests/forms_tests/tests/test_media.py4
-rw-r--r--tests/forms_tests/tests/tests.py10
-rw-r--r--tests/forms_tests/widget_tests/base.py3
12 files changed, 219 insertions, 154 deletions
diff --git a/tests/forms_tests/field_tests/test_booleanfield.py b/tests/forms_tests/field_tests/test_booleanfield.py
index d6b5121b10..f1c06c3c01 100644
--- a/tests/forms_tests/field_tests/test_booleanfield.py
+++ b/tests/forms_tests/field_tests/test_booleanfield.py
@@ -50,7 +50,8 @@ class BooleanFieldTest(SimpleTestCase):
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)
+ # Initial value may have mutated to a string due to show_hidden_initial
+ # (#19537)
self.assertTrue(f.has_changed("False", "on"))
# HiddenInput widget sends string values for boolean but doesn't clean
# them in value_from_datadict.
diff --git a/tests/forms_tests/field_tests/test_charfield.py b/tests/forms_tests/field_tests/test_charfield.py
index 2c3f9b7ebe..e1d89523f8 100644
--- a/tests/forms_tests/field_tests/test_charfield.py
+++ b/tests/forms_tests/field_tests/test_charfield.py
@@ -80,7 +80,8 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
minlength/maxlength if min_length/max_length are defined on the field
and the widget is not hidden.
"""
- # Return an empty dictionary if max_length and min_length are both None.
+ # Return an empty dictionary if max_length and min_length are both
+ # None.
f = CharField()
self.assertEqual(f.widget_attrs(TextInput()), {})
self.assertEqual(f.widget_attrs(Textarea()), {})
diff --git a/tests/forms_tests/field_tests/test_datefield.py b/tests/forms_tests/field_tests/test_datefield.py
index 65ac76319d..a8f39aa8e8 100644
--- a/tests/forms_tests/field_tests/test_datefield.py
+++ b/tests/forms_tests/field_tests/test_datefield.py
@@ -215,6 +215,6 @@ class DateFieldTest(SimpleTestCase):
try:
f.strptime("31 мая 2011", "%d-%b-%y")
except Exception as e:
- # assertIsInstance or assertRaises cannot be used because UnicodeEncodeError
- # is a subclass of ValueError
+ # assertIsInstance or assertRaises cannot be used because
+ # UnicodeEncodeError is a subclass of ValueError
self.assertEqual(e.__class__, ValueError)
diff --git a/tests/forms_tests/field_tests/test_filefield.py b/tests/forms_tests/field_tests/test_filefield.py
index 9744981471..d407df99c9 100644
--- a/tests/forms_tests/field_tests/test_filefield.py
+++ b/tests/forms_tests/field_tests/test_filefield.py
@@ -105,8 +105,8 @@ class FileFieldTest(SimpleTestCase):
# A file was not uploaded, but there is initial data
self.assertFalse(f.has_changed("resume.txt", None))
- # A file was uploaded and there is initial data (file identity is not dealt
- # with here)
+ # A file was uploaded and there is initial data (file identity is not
+ # dealt with here)
self.assertTrue(
f.has_changed(
"resume.txt", {"filename": "resume.txt", "content": "My resume"}
diff --git a/tests/forms_tests/field_tests/test_typedchoicefield.py b/tests/forms_tests/field_tests/test_typedchoicefield.py
index 52a83eca37..3537623272 100644
--- a/tests/forms_tests/field_tests/test_typedchoicefield.py
+++ b/tests/forms_tests/field_tests/test_typedchoicefield.py
@@ -19,13 +19,15 @@ class TypedChoiceFieldTest(SimpleTestCase):
self.assertEqual(1.0, f.clean("1"))
def test_typedchoicefield_3(self):
- # This can also cause weirdness: be careful (bool(-1) == True, remember)
+ # This can also cause weirdness: be careful (bool(-1) == True,
+ # remember)
f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool)
self.assertTrue(f.clean("-1"))
def test_typedchoicefield_4(self):
- # Even more weirdness: if you have a valid choice but your coercion function
- # can't coerce, you'll still get a validation error. Don't do this!
+ # Even more weirdness: if you have a valid choice but your coercion
+ # function can't coerce, you'll still get a validation error. Don't do
+ # this!
f = TypedChoiceField(choices=[("A", "A"), ("B", "B")], coerce=int)
msg = "'Select a valid choice. B is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
@@ -40,7 +42,8 @@ class TypedChoiceFieldTest(SimpleTestCase):
choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False
)
self.assertEqual("", f.clean(""))
- # If you want cleaning an empty value to return a different type, tell the field
+ # If you want cleaning an empty value to return a different type, tell
+ # the field
def test_typedchoicefield_6(self):
f = TypedChoiceField(
diff --git a/tests/forms_tests/field_tests/test_typedmultiplechoicefield.py b/tests/forms_tests/field_tests/test_typedmultiplechoicefield.py
index 6810f1ed19..e874e192d8 100644
--- a/tests/forms_tests/field_tests/test_typedmultiplechoicefield.py
+++ b/tests/forms_tests/field_tests/test_typedmultiplechoicefield.py
@@ -19,7 +19,8 @@ class TypedMultipleChoiceFieldTest(SimpleTestCase):
self.assertEqual([1.0], f.clean(["1"]))
def test_typedmultiplechoicefield_3(self):
- # This can also cause weirdness: be careful (bool(-1) == True, remember)
+ # This can also cause weirdness: be careful (bool(-1) == True,
+ # remember)
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool)
self.assertEqual([True], f.clean(["-1"]))
@@ -31,8 +32,9 @@ class TypedMultipleChoiceFieldTest(SimpleTestCase):
f.clean(["1", "2"])
def test_typedmultiplechoicefield_5(self):
- # Even more weirdness: if you have a valid choice but your coercion function
- # can't coerce, you'll still get a validation error. Don't do this!
+ # Even more weirdness: if you have a valid choice but your coercion
+ # function can't coerce, you'll still get a validation error. Don't do
+ # this!
f = TypedMultipleChoiceField(choices=[("A", "A"), ("B", "B")], coerce=int)
msg = "'Select a valid choice. B is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, msg):
@@ -49,7 +51,8 @@ class TypedMultipleChoiceFieldTest(SimpleTestCase):
self.assertEqual([], f.clean([]))
def test_typedmultiplechoicefield_7(self):
- # If you want cleaning an empty value to return a different type, tell the field
+ # If you want cleaning an empty value to return a different type, tell
+ # the field
f = TypedMultipleChoiceField(
choices=[(1, "+1"), (-1, "-1")],
coerce=int,
diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
index ae19ef1d0c..5b0c4b9a04 100644
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -81,9 +81,9 @@ class MultiValueDictLike(dict):
class FormsTestCase(SimpleTestCase):
- # A Form is a collection of Fields. It knows how to validate a set of data and it
- # knows how to render itself in a couple of default ways (e.g., an HTML table).
- # You can pass it data in __init__(), as a dictionary.
+ # A Form is a collection of Fields. It knows how to validate a set of data
+ # and it knows how to render itself in a couple of default ways (e.g., an
+ # HTML table). You can pass it data in __init__(), as a dictionary.
def test_form(self):
# Pass a dictionary to a Form's __init__().
@@ -268,9 +268,10 @@ aria-describedby="id_birthday_error">
self.assertIs(p.files, files)
def test_unbound_form(self):
- # If you don't pass any values to the Form's __init__(), or if you pass None,
- # the Form will be considered unbound and won't do any validation. Form.errors
- # will be an empty dictionary *but* Form.is_valid() will return False.
+ # If you don't pass any values to the Form's __init__(), or if you pass
+ # None, the Form will be considered unbound and won't do any
+ # validation. Form.errors will be an empty dictionary *but*
+ # Form.is_valid() will return False.
p = Person()
self.assertFalse(p.is_bound)
self.assertEqual(p.errors, {})
@@ -419,10 +420,10 @@ aria-describedby="id_birthday_error">
)
def test_cleaned_data_only_fields(self):
- # cleaned_data will always *only* contain a key for fields defined in the
- # Form, even if you pass extra data when you define the Form. In this
- # example, we pass a bunch of extra fields to the form constructor,
- # but cleaned_data contains only the form's fields.
+ # cleaned_data will always *only* contain a key for fields defined in
+ # the Form, even if you pass extra data when you define the Form. In
+ # this example, we pass a bunch of extra fields to the form
+ # constructor, but cleaned_data contains only the form's fields.
data = {
"first_name": "John",
"last_name": "Lennon",
@@ -511,8 +512,8 @@ aria-describedby="id_birthday_error">
)
def test_auto_id_true(self):
- # If auto_id is any True value whose str() does not contain '%s', the "id"
- # attribute will be the name of the field.
+ # If auto_id is any True value whose str() does not contain '%s', the
+ # "id" attribute will be the name of the field.
p = Person(auto_id=True)
self.assertHTMLEqual(
p.as_ul(),
@@ -525,8 +526,8 @@ aria-describedby="id_birthday_error">
)
def test_auto_id_false(self):
- # If auto_id is any False value, an "id" attribute won't be output unless it
- # was manually entered.
+ # If auto_id is any False value, an "id" attribute won't be output
+ # unless it was manually entered.
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
@@ -536,8 +537,9 @@ aria-describedby="id_birthday_error">
)
def test_id_on_field(self):
- # In this example, auto_id is False, but the "id" attribute for the "first_name"
- # field is given. Also note that field gets a <label>, while the others don't.
+ # In this example, auto_id is False, but the "id" attribute for the
+ # "first_name" field is given. Also note that field gets a <label>,
+ # while the others don't.
p = PersonNew(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
@@ -548,8 +550,8 @@ aria-describedby="id_birthday_error">
)
def test_auto_id_on_form_and_field(self):
- # If the "id" attribute is specified in the Form and auto_id is True, the "id"
- # attribute in the Form gets precedence.
+ # If the "id" attribute is specified in the Form and auto_id is True,
+ # the "id" attribute in the Form gets precedence.
p = PersonNew(auto_id=True)
self.assertHTMLEqual(
p.as_ul(),
@@ -636,8 +638,8 @@ aria-describedby="id_birthday_error">
'<textarea name="message" rows="10" cols="40" required></textarea>',
)
- # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
- # widget type:
+ # as_textarea(), as_text() and as_hidden() are shortcuts for changing
+ # the output widget type:
self.assertHTMLEqual(
f["subject"].as_textarea(),
'<textarea name="subject" rows="10" cols="40" required></textarea>',
@@ -660,8 +662,8 @@ aria-describedby="id_birthday_error">
'<textarea name="message" rows="80" cols="20" required></textarea>',
)
- # Instance-level attrs are *not* carried over to as_textarea(), as_text() and
- # as_hidden():
+ # Instance-level attrs are *not* carried over to as_textarea(),
+ # as_text() and as_hidden():
self.assertHTMLEqual(
f["message"].as_text(), '<input type="text" name="message" required>'
)
@@ -702,8 +704,9 @@ aria-describedby="id_birthday_error">
</select>""",
)
- # A subtlety: If one of the choices' value is the empty string and the form is
- # unbound, then the <option> for the empty-string choice will get selected.
+ # A subtlety: If one of the choices' value is the empty string and the
+ # form is unbound, then the <option> for the empty-string choice will
+ # get selected.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(
@@ -745,9 +748,9 @@ aria-describedby="id_birthday_error">
</select>""",
)
- # When passing a custom widget instance to ChoiceField, note that setting
- # 'choices' on the widget is meaningless. The widget will use the choices
- # defined on the Field, not the ones defined on the Widget.
+ # When passing a custom widget instance to ChoiceField, note that
+ # setting 'choices' on the widget is meaningless. The widget will use
+ # the choices defined on the Field, not the ones defined on the Widget.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(
@@ -1002,7 +1005,8 @@ aria-describedby="id_birthday_error">
self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>')
def test_form_with_noniterable_boundfield(self):
- # You can iterate over any BoundField, not just those with widget=RadioSelect.
+ # You can iterate over any BoundField, not just those with
+ # widget=RadioSelect.
class BeatleForm(Form):
name = CharField()
@@ -1049,7 +1053,8 @@ aria-describedby="id_birthday_error">
self.assertIs(bool(TestForm()["name"]), True)
def test_forms_with_multiple_choice(self):
- # MultipleChoiceField is a special case, as its data is required to be a list:
+ # MultipleChoiceField is a special case, as its data is required to be
+ # a list:
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField()
@@ -1226,9 +1231,9 @@ aria-describedby="id_birthday_error">
choices=[("J", "John Lennon"), ("P", "Paul McCartney")]
)
- # MultipleChoiceField rendered as_hidden() is a special case. Because it can
- # have multiple values, its as_hidden() renders multiple <input type="hidden">
- # tags.
+ # MultipleChoiceField rendered as_hidden() is a special case. Because
+ # it can have multiple values, its as_hidden() renders multiple <input
+ # type="hidden"> tags.
f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False)
self.assertHTMLEqual(
f["composers"].as_hidden(),
@@ -1260,7 +1265,8 @@ aria-describedby="id_birthday_error">
)
def test_multiple_choice_checkbox(self):
- # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
+ # MultipleChoiceField can also be used with the CheckboxSelectMultiple
+ # widget.
f = SongForm(auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
@@ -1299,9 +1305,9 @@ aria-describedby="id_birthday_error">
)
def test_checkbox_auto_id(self):
- # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
- # gets a distinct ID, formed by appending an underscore plus the checkbox's
- # zero-based index.
+ # Regarding auto_id, CheckboxSelectMultiple is a special case. Each
+ # checkbox gets a distinct ID, formed by appending an underscore plus
+ # the checkbox's zero-based index.
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
@@ -1360,7 +1366,8 @@ aria-describedby="id_birthday_error">
widget=CheckboxSelectMultiple,
)
- # The MultipleHiddenInput widget renders multiple values as hidden fields.
+ # The MultipleHiddenInput widget renders multiple values as hidden
+ # fields.
class SongFormHidden(Form):
name = CharField()
composers = MultipleChoiceField(
@@ -1379,8 +1386,8 @@ aria-describedby="id_birthday_error">
<input type="hidden" name="composers" value="P"></li>""",
)
- # When using CheckboxSelectMultiple, the framework expects a list of input and
- # returns a list of input.
+ # When using CheckboxSelectMultiple, the framework expects a list of
+ # input and returns a list of input.
f = SongForm({"name": "Yesterday"}, auto_id=False)
self.assertEqual(f.errors["composers"], ["This field is required."])
f = SongForm({"name": "Yesterday", "composers": ["J"]}, auto_id=False)
@@ -1780,9 +1787,9 @@ aria-describedby="id_birthday_error">
)
def test_dynamic_construction(self):
- # It's possible to construct a Form dynamically by adding to the self.fields
- # dictionary in __init__(). Don't forget to call Form.__init__() within the
- # subclass' __init__().
+ # It's possible to construct a Form dynamically by adding to the
+ # self.fields dictionary in __init__(). Don't forget to call
+ # Form.__init__() within the subclass' __init__().
class Person(Form):
first_name = CharField()
last_name = CharField()
@@ -1804,8 +1811,8 @@ aria-describedby="id_birthday_error">
""",
)
- # Instances of a dynamic Form do not persist fields from one Form instance to
- # the next.
+ # Instances of a dynamic Form do not persist fields from one Form
+ # instance to the next.
class MyForm(Form):
def __init__(self, data=None, auto_id=False, field_list=[]):
Form.__init__(self, data, auto_id=auto_id)
@@ -1869,8 +1876,8 @@ aria-describedby="id_birthday_error">
""",
)
- # Similarly, changes to field attributes do not persist from one Form instance
- # to the next.
+ # Similarly, changes to field attributes do not persist from one Form
+ # instance to the next.
class Person(Form):
first_name = CharField(required=False)
last_name = CharField(required=False)
@@ -1981,10 +1988,10 @@ aria-describedby="id_birthday_error">
)
def test_hidden_widget(self):
- # HiddenInput widgets are displayed differently in the as_table(), as_ul())
- # and as_p() output of a Form -- their verbose names are not displayed, and a
- # separate row is not displayed. They're displayed in the last row of the
- # form, directly after that row's form element.
+ # HiddenInput widgets are displayed differently in the as_table(),
+ # as_ul()) and as_p() output of a Form -- their verbose names are not
+ # displayed, and a separate row is not displayed. They're displayed in
+ # the last row of the form, directly after that row's form element.
class Person(Form):
first_name = CharField()
last_name = CharField()
@@ -2030,7 +2037,8 @@ aria-describedby="id_birthday_error">
'type="hidden" name="hidden_text"></div>',
)
- # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
+ # With auto_id set, a HiddenInput still gets an ID, but it doesn't get
+ # a label.
p = Person(auto_id="id_%s")
self.assertHTMLEqual(
p.as_table(),
@@ -2072,10 +2080,10 @@ aria-describedby="id_birthday_error">
'<input type="hidden" name="hidden_text" id="id_hidden_text"></div>',
)
- # 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.
+ # 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,
@@ -2159,7 +2167,8 @@ aria-describedby="id_birthday_error">
)
def test_field_order(self):
- # A Form's fields are displayed in the same order in which they were defined.
+ # A Form's fields are displayed in the same order in which they were
+ # defined.
class TestForm(Form):
field1 = CharField()
field2 = CharField()
@@ -2232,10 +2241,10 @@ aria-describedby="id_birthday_error">
)
def test_form_html_attributes(self):
- # Some Field classes have an effect on the HTML attributes of their associated
- # Widget. If you set max_length in a CharField and its associated widget is
- # either a TextInput or PasswordInput, then the widget's rendered HTML will
- # include the "maxlength" attribute.
+ # Some Field classes have an effect on the HTML attributes of their
+ # associated Widget. If you set max_length in a CharField and its
+ # associated widget is 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
password = CharField(max_length=10, widget=PasswordInput)
@@ -2277,9 +2286,10 @@ aria-describedby="id_birthday_error">
)
def test_specifying_labels(self):
- # You can specify the label for a field by using the 'label' argument to a Field
- # class. If you don't specify 'label', Django will use the field name with
- # underscores converted to spaces, and the initial letter capitalized.
+ # You can specify the label for a field by using the 'label' argument
+ # to a Field 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")
password1 = CharField(widget=PasswordInput)
@@ -2297,8 +2307,8 @@ aria-describedby="id_birthday_error">
""",
)
- # Labels for as_* methods will only end in a colon if they don't end in other
- # punctuation already.
+ # 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?")
@@ -2354,8 +2364,8 @@ aria-describedby="id_birthday_error">
""",
)
- # If label is None, Django will auto-create the label from the field name. This
- # is default behavior.
+ # If label is None, Django will auto-create the label from the field
+ # name. This is default behavior.
class UserRegistration(Form):
username = CharField(max_length=10, label=None)
password = CharField(widget=PasswordInput)
@@ -2422,16 +2432,18 @@ aria-describedby="id_birthday_error">
)
def test_initial_data(self):
- # You can specify initial data for a field by using the 'initial' argument to a
- # Field class. This initial data is displayed when a Form is rendered with *no*
- # data. It is not displayed when a Form is rendered with any data (including an
- # empty dictionary). Also, the initial value is *not* used if data for a
- # particular required field isn't provided.
+ # You can specify initial data for a field by using the 'initial'
+ # argument to a Field class. This initial data is displayed when a Form
+ # is rendered with *no* data. It is not displayed when a Form is
+ # rendered with any data (including an 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")
password = CharField(widget=PasswordInput)
- # Here, we're not submitting any data, so the initial value will be displayed.)
+ # Here, we're not submitting any data, so the initial value will be
+ # displayed.)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
@@ -2442,7 +2454,8 @@ aria-describedby="id_birthday_error">
""",
)
- # Here, we're submitting data, so the initial value will *not* be displayed.
+ # Here, we're submitting data, so the initial value will *not* be
+ # displayed.
p = UserRegistration({}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
@@ -2480,16 +2493,17 @@ Password: <input type="password" name="password" aria-invalid="true" required></
self.assertFalse(p.is_valid())
def test_dynamic_initial_data(self):
- # The previous technique dealt with "hard-coded" initial data, but it's also
- # possible to specify initial data after you've already created the Form class
- # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
- # should be a dictionary containing initial values for one or more fields in the
- # form, keyed by field name.
+ # The previous technique dealt with "hard-coded" initial data, but it's
+ # also possible to specify initial data after you've already created
+ # the Form class (i.e., at runtime). Use the 'initial' parameter to the
+ # Form constructor. This should be a dictionary containing initial
+ # values for one or more fields in the form, keyed by field name.
class UserRegistration(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
- # Here, we're not submitting any data, so the initial value will be displayed.)
+ # Here, we're not submitting any data, so the initial value will be
+ # displayed.)
p = UserRegistration(initial={"username": "django"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
@@ -2542,10 +2556,10 @@ Password: <input type="password" name="password" aria-invalid="true" required></
""",
)
- # 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'.
+ # 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."])
self.assertFalse(p.is_valid())
@@ -2567,8 +2581,8 @@ Password: <input type="password" name="password" aria-invalid="true" required></
)
def test_callable_initial_data(self):
- # The previous technique dealt with raw values as initial data, but it's also
- # possible to specify callable data.
+ # The previous technique dealt with raw values as initial data, but
+ # it's also possible to specify callable data.
class UserRegistration(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
@@ -2589,7 +2603,8 @@ Password: <input type="password" name="password" aria-invalid="true" required></
def initial_other_options():
return ["b", "w"]
- # Here, we're not submitting any data, so the initial value will be displayed.)
+ # 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,
@@ -2987,7 +3002,8 @@ Options: <select multiple name="options" aria-invalid="true" required>
'<input type="password" name="password" required></div>',
)
- # The help text is displayed whether or not data is provided for the form.
+ # The help text is displayed whether or not data is provided for the
+ # form.
p = UserRegistration({"username": "foo"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
@@ -2999,8 +3015,8 @@ Options: <select multiple name="options" aria-invalid="true" required>
'required><span class="helptext">Wählen Sie mit Bedacht.</span></li>',
)
- # help_text is not displayed for hidden fields. It can be used for documentation
- # purposes, though.
+ # 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")
password = CharField(widget=PasswordInput)
@@ -3299,9 +3315,9 @@ Options: <select multiple name="options" aria-invalid="true" required>
)
def test_subclassing_forms(self):
- # You can subclass a Form to add fields. The resulting form subclass will have
- # all of the fields of the parent Form, plus whichever fields you define in the
- # subclass.
+ # You can subclass a Form to add fields. The resulting form subclass
+ # will have all of the fields of the parent Form, plus whichever fields
+ # you define in the subclass.
class Person(Form):
first_name = CharField()
last_name = CharField()
@@ -3326,8 +3342,8 @@ Options: <select multiple name="options" aria-invalid="true" required>
<li>Instrument: <input type="text" name="instrument" required></li>""",
)
- # Yes, you can subclass multiple forms. The fields are added in the order in
- # which the parent classes are listed.
+ # Yes, you can subclass multiple forms. The fields are added in the
+ # order in which the parent classes are listed.
class Person(Form):
first_name = CharField()
last_name = CharField()
@@ -3404,8 +3420,8 @@ Options: <select multiple name="options" aria-invalid="true" required>
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.
+ # 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": "",
@@ -3420,16 +3436,16 @@ Options: <select multiple name="options" aria-invalid="true" required>
with self.assertRaises(KeyError):
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.
+ # 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."])
- # With prefixes, a single data dictionary can hold data for multiple instances
- # of the same form.
+ # 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",
@@ -3449,10 +3465,10 @@ Options: <select multiple name="options" aria-invalid="true" required>
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
- # method takes a field name and returns the prefixed field, according to
- # self.prefix.
+ # 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 method takes a field name and returns the
+ # prefixed field, according to self.prefix.
class Person(Form):
first_name = CharField()
last_name = CharField()
@@ -3504,8 +3520,9 @@ Options: <select multiple name="options" aria-invalid="true" required>
self.assertEqual(p.prefix, "bar")
def test_forms_with_null_boolean(self):
- # NullBooleanField is a bit of a special case because its presentation (widget)
- # is different than its data. This is handled transparently, though.
+ # NullBooleanField is a bit of a special case because its presentation
+ # (widget) is different than its data. This is handled transparently,
+ # though.
class Person(Form):
name = CharField()
is_cool = NullBooleanField()
@@ -3693,9 +3710,9 @@ Options: <select multiple name="options" aria-invalid="true" required>
)
def test_empty_permitted(self):
- # Sometimes (pretty much in formsets) we want to allow a form to pass validation
- # if it is completely empty. We can accomplish this by using the empty_permitted
- # argument to a form constructor.
+ # Sometimes (pretty much in formsets) we want to allow a form to pass
+ # validation if it is completely empty. We can accomplish this by using
+ # the empty_permitted argument to a form constructor.
class SongForm(Form):
artist = CharField()
name = CharField()
@@ -3713,29 +3730,31 @@ Options: <select multiple name="options" aria-invalid="true" required>
)
self.assertEqual(form.cleaned_data, {})
- # Now let's show what happens when empty_permitted=True and the form is empty.
+ # Now let's show what happens when empty_permitted=True and the form is
+ # empty.
form = SongForm(data, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
self.assertEqual(form.errors, {})
self.assertEqual(form.cleaned_data, {})
- # But if we fill in data for one of the fields, the form is no longer empty and
- # the whole thing must pass validation.
+ # But if we fill in data for one of the fields, the form is no longer
+ # empty and the whole thing must pass validation.
data = {"artist": "The Doors", "song": ""}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {"name": ["This field is required."]})
self.assertEqual(form.cleaned_data, {"artist": "The Doors"})
- # If a field is not given in the data then None is returned for its data. Lets
- # make sure that when checking for empty_permitted that None is treated
- # accordingly.
+ # If a field is not given in the data then None is returned for its
+ # data. Lets make sure that when checking for empty_permitted that None
+ # is treated accordingly.
data = {"artist": None, "song": ""}
form = SongForm(data, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
- # However, we *really* need to be sure we are checking for None as any data in
- # initial that returns False on a boolean call needs to be treated literally.
+ # However, we *really* need to be sure we are checking for None as any
+ # data in initial that returns False on a boolean call needs to be
+ # treated literally.
class PriceForm(Form):
amount = FloatField()
qty = IntegerField()
@@ -4647,7 +4666,8 @@ aria-describedby="id_age_error"></td></tr>""",
def clean(self):
data = self.cleaned_data
- # Return a different dict. We have not changed self.cleaned_data.
+ # Return a different dict. We have not changed
+ # self.cleaned_data.
return {
"username": data["username"].lower(),
"password": "this_is_not_a_secret",
@@ -4808,7 +4828,8 @@ aria-describedby="id_age_error"></td></tr>""",
)
def test_only_hidden_fields(self):
- # A form with *only* hidden fields that has errors is going to be very unusual.
+ # A form with *only* hidden fields that has errors is going to be very
+ # unusual.
class HiddenForm(Form):
data = IntegerField(widget=HiddenInput)
diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py
index 9f7012a11f..24068e79cb 100644
--- a/tests/forms_tests/tests/test_formsets.py
+++ b/tests/forms_tests/tests/test_formsets.py
@@ -192,8 +192,8 @@ class FormsFormsetTestCase(SimpleTestCase):
self.assertIs(formset.empty_form.empty_permitted, True)
def test_formset_validation(self):
- # FormSet instances can also have an error attribute if validation failed for
- # any of the forms.
+ # FormSet instances can also have an error attribute if validation
+ # failed for any of the forms.
formset = self.make_choiceformset([("Calexico", "")])
self.assertFalse(formset.is_valid())
self.assertEqual(formset.errors, [{"votes": ["This field is required."]}])
diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py
index 30ca53ba4b..d1ffc296b1 100644
--- a/tests/forms_tests/tests/test_input_formats.py
+++ b/tests/forms_tests/tests/test_input_formats.py
@@ -65,7 +65,10 @@ class LocalizedTimeTests(SimpleTestCase):
self.assertEqual(text, "13:30:00")
def test_timeField_with_inputformat(self):
- "TimeFields with manually specified input formats can accept those formats"
+ """
+ TimeFields with manually specified input formats can accept those
+ formats
+ """
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -172,7 +175,10 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:00 PM")
def test_timeField_with_inputformat(self):
- "TimeFields with manually specified input formats can accept those formats"
+ """
+ TimeFields with manually specified input formats can accept those
+ formats
+ """
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -250,7 +256,10 @@ class SimpleTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "13:30:00")
def test_localized_timeField(self):
- "Localized TimeFields in a non-localized environment act as unlocalized widgets"
+ """
+ Localized TimeFields in a non-localized environment act as unlocalized
+ widgets
+ """
f = forms.TimeField()
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -273,7 +282,10 @@ class SimpleTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "13:30:00")
def test_timeField_with_inputformat(self):
- "TimeFields with manually specified input formats can accept those formats"
+ """
+ TimeFields with manually specified input formats can accept those
+ formats
+ """
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):
@@ -378,7 +390,10 @@ class LocalizedDateTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
def test_dateField_with_inputformat(self):
- "DateFields with manually specified input formats can accept those formats"
+ """
+ DateFields with manually specified input formats can accept those
+ formats
+ """
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):
@@ -489,7 +504,10 @@ class CustomDateInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
def test_dateField_with_inputformat(self):
- "DateFields with manually specified input formats can accept those formats"
+ """
+ DateFields with manually specified input formats can accept those
+ formats
+ """
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):
@@ -567,7 +585,10 @@ class SimpleDateFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21")
def test_localized_dateField(self):
- "Localized DateFields in a non-localized environment act as unlocalized widgets"
+ """
+ Localized DateFields in a non-localized environment act as unlocalized
+ widgets
+ """
f = forms.DateField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -590,7 +611,10 @@ class SimpleDateFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21")
def test_dateField_with_inputformat(self):
- "DateFields with manually specified input formats can accept those formats"
+ """
+ DateFields with manually specified input formats can accept those
+ formats
+ """
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):
@@ -697,7 +721,10 @@ class LocalizedDateTimeTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010 13:30:00")
def test_dateTimeField_with_inputformat(self):
- "DateTimeFields with manually specified input formats can accept those formats"
+ """
+ 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"])
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -814,7 +841,10 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:00 PM 21/12/2010")
def test_dateTimeField_with_inputformat(self):
- "DateTimeFields with manually specified input formats can accept those formats"
+ """
+ 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"])
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -920,7 +950,10 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21 13:30:05")
def test_dateTimeField_with_inputformat(self):
- "DateTimeFields with manually specified input formats can accept those formats"
+ """
+ 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"]
)
diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py
index 9f6b15074c..c1d0c0a568 100644
--- a/tests/forms_tests/tests/test_media.py
+++ b/tests/forms_tests/tests/test_media.py
@@ -193,8 +193,8 @@ class FormsMediaTestCase(SimpleTestCase):
)
def test_combine_media(self):
- # Media objects can be combined. Any given media resource will appear only
- # once. Duplicated media definitions are ignored.
+ # Media objects can be combined. Any given media resource will appear
+ # only once. Duplicated media definitions are ignored.
class MyWidget1(TextInput):
class Media:
css = {"all": ("path/to/css1", "/path/to/css2")}
diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py
index 086627c9e7..866faaac4d 100644
--- a/tests/forms_tests/tests/tests.py
+++ b/tests/forms_tests/tests/tests.py
@@ -79,7 +79,8 @@ class TestTicket14567(TestCase):
self.assertIsInstance(
form.cleaned_data["multi_choice_optional"], models.query.QuerySet
)
- # While we're at it, test whether a QuerySet is returned if there *is* a value.
+ # While we're at it, test whether a QuerySet is returned if there *is*
+ # a value.
self.assertIsInstance(form.cleaned_data["multi_choice"], models.query.QuerySet)
@@ -293,8 +294,8 @@ class FormsModelTestCase(TestCase):
r2 = DefaultsForm()["callable_default"].as_widget()
self.assertNotEqual(r1, r2)
- # In a ModelForm that is passed an instance, the initial values come from the
- # instance's values, not the model's defaults.
+ # In a ModelForm that is passed an instance, the initial values come
+ # from the instance's values, not the model's defaults.
foo_instance = Defaults(
name="instance value", def_date=datetime.date(1969, 4, 4), value=12
)
@@ -370,7 +371,8 @@ class RelatedModelFormTests(SimpleTestCase):
class ManyToManyExclusionTestCase(TestCase):
def test_m2m_field_exclusion(self):
- # Issue 12337. save_instance should honor the passed-in exclude keyword.
+ # Issue 12337. save_instance should honor the passed-in exclude
+ # keyword.
opt1 = ChoiceOptionModel.objects.create(id=1, name="default")
opt2 = ChoiceOptionModel.objects.create(id=2, name="option 2")
opt3 = ChoiceOptionModel.objects.create(id=3, name="option 3")
diff --git a/tests/forms_tests/widget_tests/base.py b/tests/forms_tests/widget_tests/base.py
index c29099abf2..e30b2237c6 100644
--- a/tests/forms_tests/widget_tests/base.py
+++ b/tests/forms_tests/widget_tests/base.py
@@ -29,7 +29,8 @@ class WidgetTest(SimpleTestCase):
)
# Django escapes quotes with '&quot;' while Jinja2 uses '&#34;'.
output = output.replace("&#34;", "&quot;")
- # Django escapes single quotes with '&#x27;' while Jinja2 uses '&#39;'.
+ # Django escapes single quotes with '&#x27;' while Jinja2 uses
+ # '&#39;'.
output = output.replace("&#39;", "&#x27;")
assertEqual(output, html)