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