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 tha开发者_如何学JAVAt 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 status
field? Then it is very simple:
{{ form.status }}
Few extra words:
Form is dict-like object where fields can be accessed like this:
>>> form['field_name']
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:
>>> form.field_name
AttributeError: 'Form' object has no attribute 'field_name'
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:
- Python interpreter parses your Form class.
- Interpreter finds
__metaclass__
attribute which is inherited fromdjango.forms.Form
and is set to: DeclarativeFieldsMetaclass. - Metaclass restructures your class. Attributes are removed and
.base_fields
attribute is created. - Why
base_fields
notfields
? 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 Meta
which is sometimes used to provide additional configuration options to your form or model.
Back to templates now. You can not access form.field_name
from 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:
- Dictionary lookup
- Attribute lookup
- Method call
- List-index lookup
That means first thing template system will try to return when it encounters: {{ form.field_name }}
is: form['field_name']
.
精彩评论