Form rendering using a template instead of builtin HTML

 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
26
27
28
29
30
31
32
from django.utils.html import escape

def makeTemplatedForm(template=None):
    """Create a form class which formats its fields using the provided template.

    The template is given a dictionary containing the following key-value
    pairs:

        "label":        field label, if any,
        "errors":       list of errors, if any,
        "text":         widget rendering for an unbound form / field value for a bound form,
        "help_text":    field help text, if any
    """
    from django.template import loader
    import django.newforms as forms

    class TemplatedForm(forms.BaseForm):
        _template = template
        def __getitem__(self, name):
            "Returns a rendered field with the given name."
            #syslog.syslog("FormattingForm.__getitem__(%s)" % (name, ))
            try:
                field = self.fields[name]
            except KeyError:
                raise KeyError('Key %r not found in Form' % name)
            if not isinstance(field, forms.fields.Field):
                return field
            bf = forms.forms.BoundField(self, field, name)
            errors = [escape(error) for error in bf.errors]
            rendering = loader.render_to_string(self._template, { "errors": errors, "label": bf.label, "text": unicode(bf), "help_text": field.help_text, "field":field })
            return rendering
    return TemplatedForm

More like this

  1. NewForms Readonly / Edit Pattern by FreddieP 4 years, 5 months ago
  2. BetterForm with fieldsets and row_attrs by carljm 3 years, 3 months ago
  3. Pagination Alphabetically compatible with paginator_class by vascop 1 month ago
  4. Digg-like pagination by SmileyChris 2 years, 12 months ago
  5. load m2m fields objects by dirol 1 year, 11 months ago

Comments

alexkoval (on July 13, 2007):

Pls also take a look at my solution: http://www.djangosnippets.org/snippets/121/ I also documented both at: http://code.djangoproject.com/wiki/TemplatedForm

#

(Forgotten your password?)