简体   繁体   中英

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 or specifically .或特别是

help me please. thanks a lot

.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.

The fact that it is SafeText is important, since the Django render engine will otherwise "escape" it: without using SafeText , it would replace < with &lt; ; > with &gt; , 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)

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM