0
0
Djangoframework~5 mins

Displaying forms in templates in Django

Choose your learning style9 modes available
Introduction

Forms let users send information to your website. Displaying forms in templates shows these input fields on web pages so users can fill them out.

When you want users to register or log in.
When collecting feedback or contact details.
When letting users submit data like comments or posts.
When you need to update information through a web page.
When you want to validate user input before saving.
Syntax
Django
{% csrf_token %}
{{ form.as_p }}

{% csrf_token %} protects your form from security attacks.

{{ form.as_p }} renders the form fields wrapped in paragraph tags for simple layout.

Examples
Renders the form fields inside a table layout.
Django
{% csrf_token %}
{{ form.as_table }}
Renders the form fields as list items inside an unordered list.
Django
{% csrf_token %}
{{ form.as_ul }}
Manually render a single form field with a label for more control.
Django
{% csrf_token %}
<label for="id_name">Name:</label>
{{ form.name }}
Sample Program

This example creates a simple contact form with name, email, and message fields. The view sends the form to the template. The template displays the form fields inside paragraphs with a submit button.

Django
from django import forms
from django.shortcuts import render

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

def contact_view(request):
    form = ContactForm()
    return render(request, 'contact.html', {'form': form})

# contact.html template content:
# <form method="post">
#   {% csrf_token %}
#   {{ form.as_p }}
#   <button type="submit">Send</button>
# </form>
OutputSuccess
Important Notes

Always include {% csrf_token %} inside your form for security.

You can customize form field rendering by manually writing HTML and using {{ form.field_name }}.

Use form.as_p, form.as_table, or form.as_ul for quick layouts.

Summary

Displaying forms in templates shows input fields for users to fill.

Use {% csrf_token %} and {{ form.as_p }} to render forms safely and simply.

You can customize form display by rendering fields individually.