Django模板中的form.as_p来自何处? [英] where `form.as_p`in django templates come from?
问题描述
我有一个通用视图和一个表单模板.
我的看法是:
I have a generic view and a form template.
my view is:
class BlogCreateView(CreateView):
model = Post
template_name = "post_new.html"
fields = "__all__"
我的表单模板是:
{% extends "base.html" %}
{% block content %}
<h1>New Post</h1>
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
{% endblock content %}
现在我的问题是关于 form.as_p ,或者特别是 form .
那是哪里来的?
now my question is about form.as_p or specifically form.
Where did that come from?
请帮助我.非常感谢
推荐答案
SafeText
对象[Django-doc] ,其中包含要包含在模板中的HTML代码.
.as_p()
[Django-doc] is a method on a Form
. It produces a SafeText
object [Django-doc] that contains HTML code to be included in the template.
它是 SafeText
的事实很重要,因为Django渲染引擎否则会转义"它:如果不使用 SafeText
,它将替换<
和& lt;
;>
和& gt
等.当然,除非您自己将其包装在 SafeText
对象中,例如通过 | safe
strong>模板过滤器[Django-doc] .
The fact that it is SafeText
is important, since the Django render engine will otherwise "escape" it: without using SafeText
, it would replace <
with <
; >
with >
, etc. Unless of course you wrap it in a SafeText
object yourself, for example through the |safe
template filter [Django-doc].
例如,我们可以定义一个在文档中:
We can for example define a form like in the documentation:
class OptionalPersonForm(forms.Form):
first_name = forms.CharField()
last_name = forms.CharField()
nick_name = forms.CharField(required=False)
如果我们随后构造一个表单对象,则可以调用 .as_p()
方法:
If we then construct a form object, we can call the .as_p()
method:
>>> OptionalPersonForm().as_p()
'<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" required id="id_last_name"></p>\n<p><label for="id_nick_name">Nick name:</label> <input type="text" name="nick_name" id="id_nick_name"></p>'
>>> type(OptionalPersonForm().as_p())
<class 'django.utils.safestring.SafeText'>
Django表单具有三种流行的渲染方法: .as_p
,"> .as_ul()
[Django-doc] .区别在于它们对HTML的呈现略有不同:作为段落,表格或无序的HTML列表.
Django forms have three popular rendering methods: .as_p
, .as_table()
[Django-doc] and .as_ul()
[Django-doc]. The difference is that these render the HTML slightly differently: as paragraphs, a table or unordered HTML list.
这篇关于Django模板中的form.as_p来自何处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!