Login

Changing the look of newforms as_table with a custom BaseForm

Author:
bikeshedder
Posted:
June 4, 2007
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

I wanted to mark rows with an erroneous input with 'class="error"' and move the errorlist below the input tag so I wrote a NormalRowFormatter which behaves like a format string by overwriting __mod__.

Examples:

class MyForm(PrettyBaseForm, forms.Form):
    # add your fields here

SomethingForm = form_for_model(Something, form=PrettyBaseForm)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django import newforms as forms


class PrettyBaseForm (forms.BaseForm):

    class NormalRowFormatter(object):

        def _error_class(self, errors):
            if errors:
                return ' class="error"'
            else:
                return ''

        def __mod__(self, d):
            return u'<tr%s>' % self._error_class(d['errors']) \
                 + u'<th>%(label)s</th><td>%(field)s%(errors)s%(help_text)s</td></tr>' % d

    def as_table(self):
        return self._html_output(
            PrettyBaseForm.NormalRowFormatter(),
            u'<tr><td colspan="2">%s</td></tr>', # unused
            u'</td></tr>',
            u'<br />%s',
            False
        )

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

Please login first before commenting.