{{ field }} 如何在Django模板中显示字段小部件?

3 投票
1 回答
1003 浏览
提问于 2025-04-18 00:34

根据我对django模板语言的理解,{{ variable }}会通过以下几种方式显示变量:

  1. 变量本身就是一个字符串
  2. 变量是一个可以调用的函数,返回一个字符串
  3. 变量的字符串表示形式

下面是一个演示:

>>> from django.template import Template, Context
>>> template = Template("Can you display {{ that }}?")
>>> context = Context({"that":"a movie"})          #a string variable
>>> template.render(context)
u'Can you display a movie?'
>>> context2 = Context({"that": lambda:"a movie"}) #a callable
>>> template.render(context2)
u'Can you display a movie?'
>>> class Test:
...   def __unicode__(self):
...     return "a movie"
... 
>>> o = Test()
>>> context3 = Context({"that":o}) #the string representation
>>> template.render(context3)
u'Can you display a movie?'

显然,表单字段不属于这几种情况。

再来看一个演示:

>>> from django import forms
>>> class MyForm(forms.Form):
...   name = forms.CharField(max_length=100)
... 
>>> form = MyForm({"name":"Django"})
>>> name_field = form.fields["name"]
>>> name_field #a string variable?
<django.forms.fields.CharField object at 0x035090B0>
>>> str(name_field) #the string represetation?
'<django.forms.fields.CharField object at 0x035090B0>'
>>> name_field() #a callable?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'CharField' object is not callable
>>> context4 = Context({"that":name_field})
>>> template.render(context4)
u'Can you display &lt;django.forms.fields.CharField object at 0x035090B0&gt;?'

看看最后那部分,它实际上并没有像真正的模板那样渲染。

那么,怎样的模板才能正确显示一个表单呢:

{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
    </div>
{% endfor %}

在这种情况下,字段是如何转换成相应的控件的呢?

1 个回答

3

这其实就是关键所在:

>>> str(form['name'])
'<input id="id_name" type="text" name="name" value="Django" maxlength="100" />'

我想这就是你模板中的 for 循环所遍历的内容。

撰写回答