from django import newforms as forms
from django.newforms.forms import BoundField
from django.template import Context, loader
class TemplatedForm(forms.Form):
'''
template newforms/form.html:
% for field in bound_fields %}
{% include "newforms/field.html" %}
{% endfor %}
template newforms/field.html:
{{ field }}
{% if field.errors %}{{ field.errors }}{% endif %}
{% if field.help_text %}
({{ field.help_text }})
{% endif %}
'''
def output_via_template(self):
"Helper function for fieldsting fields data from form."
bound_fields = [BoundField(self, field, name) for name, field \
in self.fields.items()]
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()
# example usage in view
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)