{{ form.as_p }} – Render Django Forms as paragraph

Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article, Form is rendered as paragraphs in the template.

{{ form.as_p }} – Render Django Forms as paragraph

Illustration of {{ form.as_p }} using an Example. Consider a project named geeksforgeeks having an app named geeks.

Refer to the following articles to check how to create a project and an app in Django.

Let’s create a sample Django Form to render it and show as an example. In geeks > forms.py, enter following code

filter_none

edit
close

play_arrow

link
brightness_4
code

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())

chevron_right


Now we need a View to render this form into a template. Let’s create a view,



filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


Finally, we will create the template where we need the form to be placed. In templates > home.html,

filter_none

edit
close

play_arrow

link
brightness_4
code

<form action = "" method = "post">
    {% csrf_token %}
    {{form.as_p }}
    <input type="submit" value=Submit">
</form>

chevron_right


Here {{ form.as_p }} will render them wrapped in <p> tags. Let’s check whether this is working acordingly or not. Open http://localhost:8000/


Let’s 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,

Other Methods




My Personal Notes arrow_drop_up

Software Developer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : NaveenArora

Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.