[Django]-How do you render a django form in a view?

9👍

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.

4👍

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.

0👍

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?

Leave a comment