Processing a table of forms in Django

I’m using Django for my current web interface work at Mitel, and I’m constantly finding that I have to push the limit of my knowledge in Django to make it work with many of the requirements that I have.

One example is instead of displaying a single form for an object in the database, on one page I need a table of such objects, with each row in the table representing a single object. How does one do this with Django newforms?

Well, some time in #django on freenode worked that out. It doesn’t really stand out in the docs, but it’s there. You can use a form prefix on each unique form. This results in mangling the names of the widgets in that form with the prefix, thus allowing one to parse out the fields applying to that instance later.

So, if you have a list of dictionaries, for example, representing the model data, when you display the form you could do this:

forms = []
for d in dictionaries:
   forms.append(MyForm(d, prefix=d['key'])

assuming some unique key ‘key’ in each dictionary. Pass ‘forms’ to your context when you render, and render the table like normal, except by iterating a list of forms.

<table class="sometable">
   {% for form in forms %}
   <tr>
      <td>{{ form.foo }}</td>
      <td>{{ form.bar }}</td>
   </tr>
   {% endfor %}
</table>

And then in the POST submission you pull them back out again.

if request.method == "POST":
   forms = []
   for d in dictionaries:
      form = MyForm(request.POST, prefix=d['key']
      if form.is_valid():
         forms.append(form)
      else:

Pretty cool, says I.

Post a Comment

Required fields are marked *

*
*