[Django]-Django, how to parse a single form field (HTML) without a for loop

9👍

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:

  1. Python interpreter parses your Form class.
  2. Interpreter finds __metaclass__ attribute which is inherited from django.forms.Form and is set to: DeclarativeFieldsMetaclass.
  3. Metaclass restructures your class. Attributes are removed and .base_fields attribute is created.
  4. Why base_fields not fields? 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'].

👤Ski

Leave a comment