views:

155

answers:

3
for field in FIELDS:
    row = []
    row.append("<tr>")
    row.append("<td>" + str(myform.fields.get(field)) + "</td>")
    row.append("</tr>")

    custom_fields.append("".join(row))

When I give the custom_fields variable to the template, all I'm getting is:

<tr><td><django.forms.widgets.CheckboxInput object at 0x1fa7d90></td></tr>

How can I get the form rendered properly?


This is what I'm going to be doing eventually:

form1 = CustomForm1()
form2 = CustomForm2()
form3 = CustomForm3()

for field in FIELDS:
    row = []
    row.append("<tr>")
    row.append("<td>" + str(form1.fields.get(field)) + "</td>")
    row.append("<td>" + str(form2.fields.get(field)) + "</td>")
    row.append("<td>" + str(form3.fields.get(field)) + "</td>")
    row.append("</tr>")

    custom_fields.append("".join(row))

So I can display all form fields together in one table.

A: 

Are you passing the list of fields to the template by itself? The fields need to be part of an object derived from forms.Form in order for the template to render it correctly.

Given that you've got the call to myform.fields.get() it looks like you have a Form object; what exactly are you trying to do with this list of fields?

Meredith L. Patterson
+3  A: 

As explained here, form instances have some predefined rendering methods like as_table, as_ul, as_p that you can use in templates.

as_table seems to cut your needs but in case not, you can easily add your custom rendering methods to your own form classes. Having a look at django.forms.forms.BaseForm class is a good idea at this point.

utku_karatas
+1. Django provides an inteface to render your forms for you, so best to use that.
anschauung
A: 

I just figured this out. It's form[field] instead of form.fields[field]

>>> f = MyForm()
>>> f
<myform.forms.MyForm object at 0x1fa7810>

>>> f['myfield']
<django.forms.forms.BoundField object at 0x20c7e50>

>>> f.fields['myfield']
<django.forms.fields.BooleanField object at 0x1fa7850>

so form.fields is a list of all unbound fields, and form.__getitem__ is a callable that returns the bound fields.

nbv4