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.
Displaying forms in templates in 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.
{% csrf_token %}
{{ form.as_table }}{% csrf_token %}
{{ form.as_ul }}{% csrf_token %}
<label for="id_name">Name:</label>
{{ form.name }}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.
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>
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.
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.