Here is the relevant SO question: Django and Fieldsets on Modelform , although this seems a bit redundant for what I want to accomplish. Also, here is one of the possible hacks, although I'm curious to see how Django experts solve this problem.
(0) Define a python field set object that is iterable so that we can iterate over it in the django template:
from django.forms.forms import BoundField class FieldSet(object): def __init__(self,form,fields,legend='',cls=None): self.form = form self.legend = legend self.fields = fields self.cls = cls def __iter__(self): for name in self.fields: field = self.form.fields[name] yield BoundField(self.form, field, name)
(1) In the view, use:
fieldsets = (FieldSet(form_object, ('field_name1','field_name2'), legend='Div env 1', cls="class1"), FieldSet(form_object, ('field_name3','field_name4'), legend="Div env 2", cls="class2")) return render_to_response('my_form.html', {'form': form_object,'fieldsets':fieldsets}, context_instance=RequestContext(request))
(2) Now in the template, do:
{% for set in fieldsets %} <fieldset{% if set.cls %} class="{{ set.cls }}"{% endif %}> <legend>{{ set.legend }}</legend> {% for field in set %} {{ field.label}} : {{ field }} {% endfor %} </fieldset> {% endfor %}
Please note that you can replace the fieldset
tag with a div
tag to solve my specific issue.
+++ Most of this answer is extracted from Michael Kowalczyk on this blog . +++