[Answered ]-Form in django form.as_p different

2👍

Forms have a few optional rendering options in django: as_p, as_table, as_ul

Without any rendering options:

<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Send"/>
</form>

Will render a form that looks like this:

<form action="" method="post" enctype="multipart/form-data">
<input>
<input>
<input>
...
</form>

Adding the rendering option as_p just wraps the input fields in paragraph tags. So adding the as_p here:

<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send"/>
</form>

Will render a form that looks like this:

<form action="" method="post" enctype="multipart/form-data">
<p><input></p>
<p><input></p>
<p><input></p>
...
</form>

0👍

To see what {{ form.as_p }} outputs, you can click ‘view source’ in your browser and see the rendered html.

I would not recommend rendering the fields manually as in your first example. It’s easy to make mistakes. For example you have forgotten the opening {{ in id="form.title}}".

If you need to add a custom class to the input, you can do this by changing the field’s widget. Alternatively, you might find crispy forms useful.

Leave a comment