Environment: Python 2.7.5 + Django 1.6
With Django, we can define a form in a declarative way, as follows:
#-*-Coding:utf-8-*-from Django Import formsclass simpleform (forms. Form): field_a = forms. Charfield (max_length=100) field_b = forms. Charfield (max_length=100)
It's comfortable to write, but the problem comes when I initialize this form, for example:
From polls.forms import Simpleform
SF = Simpleform ({' field_a ': ' Value of field_a ', ' field_b ': ' Value of Field_b '})
Then, executing dir (SF) in the Python shell, and discovering that the instance does not have both field_a and Field_b properties, obviously we cannot refer to the fields on SF as sf.field_a. But obviously we can refer to the form's field in the template as {{form_name.field_name}}, what's going on?
A survey found that the mechanism behind the implementation is also more tortuous. First, what should we do if we want to refer to the fields in the form? It should be written like this: sf[' field_a ']
Why do you write this? On the code, Django.forms.BaseForm the __getitem__ method:
def __getitem__ (self, name): "Returns a BoundField with the given name." Try: field = Self.fields[name] except Keyerror: raise Keyerror (' Key%r not found in Form '% name) return B Oundfield (Self, field, name)
This turns the baseform into a dict-like container, so you can use the syntax above to refer to the fields in the form.
The new question comes again, why can I refer to the form's field in the template as {{form_name.field_name}}? See Django's official Documentation: Https://docs.djangoproject.com/en/1.6/topics/templates/#variables. The original Django template engine encountered an expression such as {{form_name.field_name}} that would run a dictionary lookup on the Form_name object, so the template engine actually ran sf[' field_a ' when evaluating {{sf.field_a}} , the truth is out.
In addition, the type of simpleform in the above is actually django.forms.DeclarativeFieldsMetaclass. This meta-class actually converts all the fields in Simpleform declared in declarative syntax (and also the declarative fields in the parent class) through the Get_declared_fields method to a dict and assigns the Dict value to the class that will be generated base_ Fields property, and then generates a new class based on Simpleform.