diff --git a/django/newforms/forms.py b/django/newforms/forms.py index 36dd36fcce..15b24b39fe 100644 --- a/django/newforms/forms.py +++ b/django/newforms/forms.py @@ -124,6 +124,33 @@ class Form(StrAndUnicode): output.append(str_hidden) return u'\n'.join(output) + def as_p(self): + "Returns this form rendered as HTML

s." + top_errors = self.non_field_errors() + output, hidden_fields = [], [] + for name, field in self.fields.items(): + bf = BoundField(self, field, name) + bf_errors = bf.errors # Cache in local variable. + if bf.is_hidden: + if bf_errors: + top_errors.extend(['(Hidden field %s) %s' % (name, e) for e in bf_errors]) + hidden_fields.append(unicode(bf)) + else: + if bf_errors: + output.append(u'

%s

' % bf_errors) + output.append(u'

%s %s

' % (bf.label_tag(escape(bf.verbose_name+':')), bf)) + if top_errors: + output.insert(0, u'

%s

' % top_errors) + if hidden_fields: # Insert any hidden fields in the last

. + str_hidden = u''.join(hidden_fields) + if output: + last_td = output[-1] + # Chop off the trailing '

' and insert the hidden fields. + output[-1] = last_td[:-4] + str_hidden + '

' + else: # If there aren't any '

's in the output, just append the hidden fields. + output.append(str_hidden) + return u'\n'.join(output) + def non_field_errors(self): """ Returns an ErrorList of errors that aren't associated with a particular diff --git a/tests/regressiontests/forms/tests.py b/tests/regressiontests/forms/tests.py index 16e56a8212..779db97528 100644 --- a/tests/regressiontests/forms/tests.py +++ b/tests/regressiontests/forms/tests.py @@ -1368,6 +1368,13 @@ False

  • First name:
  • Last name:
  • Birthday:
  • +>>> print p.as_p() +

    +

    First name:

    +

    +

    Last name:

    +

    +

    Birthday:

    If you don't pass any values to the Form's __init__(), or if you pass None, the Form won't do any validation. Form.errors will be an empty dictionary *but* @@ -1389,6 +1396,10 @@ False
  • First name:
  • Last name:
  • Birthday:
  • +>>> print p.as_p() +

    First name:

    +

    Last name:

    +

    Birthday:

    Unicode values are handled properly. >>> p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'}) @@ -1396,6 +1407,8 @@ Unicode values are handled properly. u'First name:\nLast name:\nBirthday:' >>> p.as_ul() u'
  • First name:
  • \n
  • Last name:
  • \n
  • Birthday:
  • ' +>>> p.as_p() +u'

    First name:

    \n

    Last name:

    \n

    Birthday:

    ' >>> p = Person({'last_name': u'Lennon'}) >>> p.errors @@ -1432,14 +1445,18 @@ If it's a string that contains '%s', Django will use that as a format string into which the field's name will be inserted. It will also put a