Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Rendering Forms in Templates
Django forms can be rendered in templates using built-in rendering methods - {{ form.as_p }}, {{ form.as_div }}, or field-by-field for full control. Always include {% csrf_token %} for security.
Form Rendering Methods
- {{ form.as_p }} - Each field in a <p> tag
- {{ form.as_div }} - Each field in a <div> (Django 4.1+)
- {{ form.as_table }} - Each field in a <tr>
- {{ form.field_name }} - Render individual fields
- {{ form.field_name.label_tag }} - Field label
- {{ form.field_name.errors }} - Field-specific errors
- {{ form.non_field_errors }} - Form-level errors
- {% csrf_token %} - REQUIRED for POST forms
Form Rendering
# Quick rendering
# <form method="post">
# {% csrf_token %}
# {{ form.as_p }}
# <button type="submit">Submit</button>
# </form>
# Full control - field by field
# <form method="post">
# {% csrf_token %}
#
# <div class="form-group">
# {{ form.title.label_tag }}
# {{ form.title }}
# {% if form.title.errors %}
# <span class="error">{{ form.title.errors.0 }}</span>
# {% endif %}
# </div>
#
# <div class="form-group">
# {{ form.content.label_tag }}
# {{ form.content }}
# {% for error in form.content.errors %}
# <span class="error">{{ error }}</span>
# {% endfor %}
# </div>
#
# {% if form.non_field_errors %}
# <div class="errors">
# {% for error in form.non_field_errors %}
# <p>{{ error }}</p>
# {% endfor %}
# </div>
# {% endif %}
#
# <button type="submit">Submit</button>
# </form>?? Tip
Tip
Always use {% csrf_token %} in POST forms. For AJAX, include the CSRF token in request headers.
QuerySets are LAZY - no DB hit until evaluated.
?? Common Mistake
Warning
Forgetting {% csrf_token %} in forms. Django will reject the POST request with a 403 Forbidden error.
?? Practice Task
Note
(1) Create a form with {% csrf_token %}. (2) Handle POST in the view. (3) Redirect after successful submission.
Quick Quiz
Key Takeaways
- Django forms can be rendered in templates using built-in rendering methods - {{ form.
- {{ form.as_p }} - Each field in a <p> tag
- {{ form.as_div }} - Each field in a <div> (Django 4.1+)
- {{ form.as_table }} - Each field in a <tr>