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

时间:2014-03-30 18:26:38

标签: python django

根据我对django template language的理解,{{ variable }}将通过以下方式之一显示该变量:

  1. 变量是一个字符串本身
  2. 该变量是一个返回字符串
  3. 的可调用对象
  4. 变量
  5. 的字符串表示形式

    演示会议:

    >>> 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 个答案:

答案 0 :(得分:3)

这一切都归结为:

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

我想这就是模板中的for循环迭代了。