Version 1 (modified by alex@…, 18 years ago) ( diff )

Example of rendering newform via template

Subclassing newforms Form.form to rendering form via django template

Sometimes standard methods of rendering HTML/XML/other content of the django.newforms is not enough to completely satisfy all web design needs. So sometimes it is better to customize your forms completely.

Using templates to render output as HTML or XML is straighforward and uses less code then as_table() counterpart implemented now in the core newforms, so I hope technique explained here will be helpful.

The above example has been crated specifically to mark required fields with red asterisk. In fact all you need to do to use this, is to add 3 small files to your project, and replace forms.Form to TemplatedForm class. Step by step explanations:

  1. Create file in your project:

yourproject/utils/newforms.py:

from django import newforms as forms
from django.newforms.forms import BoundField
from django.template import Context, loader

class TemplatedForm(forms.Form):
    def output_via_template(self):
        "Helper function for fieldsting fields data from form."
        bound_fields = []
        for name, field in self.fields.items():
            bf = BoundField(self, field, name)
            bound_fields.append(bf)
        
        c = Context(dict(form = self, bound_fields = bound_fields))
        t = loader.get_template('newforms/form.html')
        return t.render(c)
        
    def __str__(self):
        return self.output_via_template()
  1. Create HTML templates, here is very simple template form form and field:

file: templates/newforms/form.html

{% for field in bound_fields %} {% include "newforms/field.html" %} {% endfor %}

file: templates/newforms/field.html

<tr{% if field.errors %} class="errors" {% endif%}>
  <th>
    <label for="id_{{ field.name }}">{{ field.label }}{% if field.field.required %}<span class="required">*</span>{% endif %}:</label>
  </th>
  <td>
    {{ field }}
    {% if field.errors %}{{ field.errors }}{% endif %}
    {% if field.help_text %}
    <p class="helptext">({{ field.help_text }})</p>
    {% endif %}
  </td>
</tr>

Example of usage from view.py: file: myproject/myapp/myview.py

class PersonalInfoForm(TemplatedForm):
    school_or_institution = forms.CharField(max_length=100,required=False)
    first_name = forms.CharField(max_length=100,required=False)
    last_name = forms.CharField(max_length=100,required=False)
    email = forms.EmailField()
    personal_website_url = forms.CharField(max_length=100,required=False)
    button = forms.CharField(required=False,widget=forms.HiddenInput)
Note: See TracWiki for help on using the wiki.
Back to Top