gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:38:34 27 4
gpt4 key购买 nike

据我了解django template language , {{ 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 %}

在这种情况下,字段如何转换为相应的小部件?

最佳答案

这一切归结为:

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

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

关于python - {{ field }} 如何在 django 模板中显示字段小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22747982/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com