The {{ form.as_p }} method renders Django form fields as HTML paragraphs. Each form field, along with its label and validation errors, is wrapped inside a <p> element. This provides a quick way to display forms with minimal template code while maintaining a clean vertical layout.
Example:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
</form>
Using {{ form.as_p }} to Render Django Forms
Example: Create a project named geeksforgeeks having an app named geeks and create a sample Django Form to render it.
In geeks /forms.py,
from django import forms
# creating a form
class InputForm(forms.Form):
first_name = forms.CharField(max_length = 200)
last_name = forms.CharField(max_length = 200)
roll_number = forms.IntegerField(
help_text = "Enter 6 digit roll number"
)
password = forms.CharField(widget = forms.PasswordInput())
In views.py,
from django.shortcuts import render
from .forms import InputForm
# Create your views here.
def home_view(request):
context ={}
context['form']= InputForm()
return render(request, "home.html", context)
In templates /home.html,
<form action = "" method = "post">
{% csrf_token %}
{{form.as_p }}
<input type="submit" value=Submit">
</form>
Open http://localhost:8000/:
Check the source code whether the form is rendered as a paragraph or not. By rendering as a paragraph it is meant that all input fields will be enclosed in <p> tags. Here is the demonstration.
Explanation:
- Create Form Class: InputForm defines the form fields and their validation rules.
- Instantiate Form: The view creates an instance of InputForm.
- Pass Form to Template: The form object is included in the template context.
- Render Form: {{ form.as_p }} converts form fields into HTML paragraph elements.
- Add CSRF Protection: {% csrf_token %} protects the form from CSRF attacks.
- Display Form: Django renders the generated HTML in the browser.
Note: {{ form.as_p }} controls only the HTML layout of the form fields. It does not affect form validation, submission handling, or database operations.
When to Use form.as_p
- Suitable for forms displayed in a simple vertical layout.
- Requires minimal template code.
- Useful for quick prototypes and small forms.
- Easier to style with CSS than table-based layouts.
Other Form Rendering Methods
| Method | Output |
|---|---|
| {{ form.as_p }} | Renders fields inside <p> tags |
| {{ form.as_table }} | Renders fields inside table rows (<tr>) |
| {{ form.as_ul }} | Renders fields inside list items (<li>) |
Related Articles
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
{{ form.as_table }}
{{ form.as_ul }}