I want to parse the fields of my Modelform separately and not in a for loop. And i want some fields to parse the Django HTML for that element.
I have this:
<form action="#" method="POST" name="notifictaionForm">
<ul>
<li><label>{{ form.fields.title.label }}</label> <span>{{ notification.title }}</span></li>
<li><label>{{ form.fields.create_date.label }}</label> <span>{{ notification.create_date }}</span></li>
<li><label>{{ form.fields.description.label }}</label> <span>{{ notification.description }}</span></li>
<li><label>{{ form.fields.status.label }}</label> <span>{{ form.fields.status.??? }}</span></li>
</ul>
</form>
So i can parse the name of the field but not the HTML element, i want at the ??? in the template code to parse the Django HTML form element.
Does somebody know how to do this?
If I’ve understood you well, You want django’s auto-generated html for
statusfield? Then it is very simple:Few extra words:
Form is dict-like object where fields can be accessed like this:
Declared fields are stored in
form.fields, a SortedDict object. So you can use this variable to access fields, however recommended way is always the shortest way.If you are new to Python, you might wonder how is it so that you declare fields as attributes, however you are not able to access them from python code like this:
Well it is because classes in python aren’t static, the meta-class can be used to build all kind of new things out of class definition. Django makes use of it to create a friendly API. Basically it goes like this:
__metaclass__attribute which is inherited fromdjango.forms.Formand is set to: DeclarativeFieldsMetaclass..base_fieldsattribute is created.base_fieldsnotfields? Well it is another story, this has do with how fields which comes from models in ModelForm are separated from fields declared in form class.But do not confuse metaclasses with the
class Metawhich is sometimes used to provide additional configuration options to your form or model.Back to templates now. You can not access
form.field_namefrom python code, why then it is possible in template? As described in django documentation, when the template system encounters a dot, it tries the following lookups, in this order:That means first thing template system will try to return when it encounters:
{{ form.field_name }}is:form['field_name'].