[英]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__"
and my form template is:我的表单模板是:
{% 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 %}
now my question is about form.as_p or specifically
form .
现在我的问题是关于form.as_p或特别是
form 。
Where did that come from?
那个是从哪里来的?
help me please.请帮帮我。 thanks a lot
多谢
.as_p()
[Django-doc] is a method on a Form
. .as_p()
[Django-doc]是Form
上的一个方法。 It produces a SafeText
object [Django-doc] that contains HTML code to be included in the template.它生成一个
SafeText
对象 [Django-doc] ,其中包含要包含在模板中的 HTML 代码。
The fact that it is SafeText
is important, since the Django render engine will otherwise "escape" it: without using SafeText
, it would replace <
with <
它是
SafeText
的事实很重要,因为否则 Django 渲染引擎将“转义”它:如果不使用SafeText
,它会将<
替换为<
; ;
>
with >
>
与>
, etc. Unless of course you wrap it in a SafeText
object yourself, for example through the |safe
template filter [Django-doc] .等。当然,除非您自己将它包装在
SafeText
对象中,例如通过|safe
模板过滤器 [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)
If we then construct a form object, we can call the .as_p()
method:如果我们然后构造一个表单对象,我们可以调用
.as_p()
方法:
>>> 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 forms have three popular rendering methods: .as_p
, .as_table()
[Django-doc] and .as_ul()
[Django-doc] . Django 表单具有三种流行的渲染方法:
.as_p
、 .as_table()
[Django-doc]和.as_ul()
[Django-doc] 。 The difference is that these render the HTML slightly differently: as paragraphs, a table or unordered HTML list.不同之处在于它们呈现的 HTML 略有不同:作为段落、表格或无序列表的 HTML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.