Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixed #23167 -- Added BaseForm.__repr__()

Thanks Keryn Knight for the idea.
  • Loading branch information...
commit a6691e5dcfdfd1529987be3bdcf06e7ab9948356 1 parent 0396cd8
Areski Belaid areski authored timgraham committed
Showing with 36 additions and 0 deletions.
  1. +12 −0 django/forms/forms.py
  2. +24 −0 tests/forms_tests/tests/test_forms.py
12 django/forms/forms.py
View
@@ -134,6 +134,18 @@ def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
def __str__(self):
return self.as_table()
+ def __repr__(self):
+ if self._errors is None:
+ is_valid = "Unknown"
+ else:
+ is_valid = self.is_bound and not bool(self._errors)
+ return '<%(cls)s bound=%(bound)s, valid=%(valid)s, fields=(%(fields)s)>' % {
+ 'cls': self.__class__.__name__,
+ 'bound': self.is_bound,
+ 'valid': is_valid,
+ 'fields': ';'.join(self.fields),
+ }
+
def __iter__(self):
for name in self.fields:
yield self[name]
24 tests/forms_tests/tests/test_forms.py
View
@@ -2338,3 +2338,27 @@ def clean(self):
<tr><th><label for="id_first_name">First name:</label></th><td><input id="id_first_name" name="first_name" type="text" value="John" /></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td><input id="id_last_name" name="last_name" type="text" value="Lennon" /></td></tr>"""
)
+
+ def test_baseform_repr(self):
+ """
+ Test for baseForm method __repr__
+ """
+ p = Person()
+ self.assertEqual(repr(p), "<Person bound=False, valid=Unknown, fields=(first_name;last_name;birthday)>")
+ p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'})
+ self.assertEqual(repr(p), "<Person bound=True, valid=Unknown, fields=(first_name;last_name;birthday)>")
+ p.is_valid()
+ self.assertEqual(repr(p), "<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>")
+ p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'})
+ p.is_valid()
+ self.assertEqual(repr(p), "<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>")
+
+ def test_baseform_repr_dont_trigger_validation(self):
+ """
+ Test to verify that __repr__ method don't trigger the validation
+ """
+ p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'})
+ repr(p)
+ self.assertRaises(AttributeError, lambda: p.cleaned_data)
+ self.assertFalse(p.is_valid())
+ self.assertEqual(p.cleaned_data, {'first_name': 'John', 'last_name': 'Lennon'})
Please sign in to comment.
Something went wrong with that request. Please try again.