2014-03-30 59 views
3

根據我的django template language的理解,{{ variable }}將通過以下方式之一顯示變量:{{field}}如何在django模板中顯示字段小部件?

  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 %} 

如何領域轉變爲相應部件在這種情況下?

回答

3

這一切都歸結到:

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

我想這是在什麼for循環在你的模板進行迭代。

+0

這真是太棒了!現在有意義的是'CharField'的form.fields [「name」]和'BoundField'的form [「name」]之間的區別。我想我需要調查這種差異。 – MadeOfAir

相關問題