Forms in Django can be seamlessly rendered in templates using Django's built-in form handling system. Templates control how fields, labels, and validation errors appear on the page.
Django provides helper methods such as {{ form }}, {{ form.as_p }}, {{ form.as_table }}, and manual field access for full control over layout.
// Automatically renders all form fields using paragraph tags
{% extends "base.html" %}
{% block content %}
<h2>Contact Us</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
// Manually rendering each form field for layout control
{% extends "base.html" %}
{% block content %}
<h2>Contact Us</h2>
<form method="post">
{% csrf_token %}
<div>
<label for="{{ form.name.id_for_label }}">Name</label>
{{ form.name }}
</div>
<div>
<label for="{{ form.email.id_for_label }}">Email</label>
{{ form.email }}
</div>
<div>
<label for="{{ form.message.id_for_label }}">Message</label>
{{ form.message }}
</div>
<button type="submit">Submit</button>
</form>
{% endblock %}
// Displays validation errors below each form field
{% extends "base.html" %}
{% block content %}
<h2>Contact Us</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
{% for field in form %}
{% if field.errors %}
<div class="errors">
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endif %}
{% endfor %}
<button type="submit">Submit</button>
</form>
{% endblock %}
// Uses table layout for structured form display
{% extends "base.html" %}
{% block content %}
<h2>Contact Us</h2>
<form method="post">
{% csrf_token %}
<table>
<tr>
<td><label for="{{ form.name.id_for_label }}">Name</label></td>
<td>{{ form.name }}</td>
</tr>
<tr>
<td><label for="{{ form.email.id_for_label }}">Email</label></td>
<td>{{ form.email }}</td>
</tr>
<tr>
<td><label for="{{ form.message.id_for_label }}">Message</label></td>
<td>{{ form.message }}</td>
</tr>
</table>
<button type="submit">Submit</button>
</form>
{% endblock %}
Click the buttons below to see how Django generates HTML differently based on the rendering method you choose.
{{ form.as_p }} for fast prototyping.{% csrf_token %}.as_p.