Rendering Forms

Output a form in a template and style its fields.

Syntax{{ form.as_p }}

You render a form in a template by printing it. Django offers helpers like {{ form.as_p }} that wrap each field in a paragraph. You can also loop over fields for full control.

Always place form fields inside a <form> element with the correct method and a submit button.

Example

Example · python
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Send</button>
</form>

<!-- Or render field by field: -->
<!-- {{ form.name.label_tag }} {{ form.name }} {{ form.name.errors }} -->

When to use it

  • A developer renders form fields individually to wrap each input in a custom Bootstrap card layout.
  • A team uses form.errors to display field-specific error messages next to each input in a custom template.
  • A developer uses as_table() for a quick admin-style form layout during internal tool development.

More examples

Render individual form fields

Renders each field's label, widget, and errors separately for full control over HTML structure.

Example · html
<form method="post">
  {% csrf_token %}
  <div class="mb-3">
    {{ form.title.label_tag }}
    {{ form.title }}
    {{ form.title.errors }}
  </div>
  <div class="mb-3">
    {{ form.body.label_tag }}
    {{ form.body }}
    {{ form.body.errors }}
  </div>
  <button type="submit">Save</button>
</form>

Render all fields with as_p

Uses the as_p() shortcut to wrap every field in a paragraph tag for fast prototyping.

Example · html
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Submit</button>
</form>

Display non-field errors

Shows how to display errors from the form's cross-field clean() method above the fields.

Example · html
<form method="post">
  {% csrf_token %}
  {% if form.non_field_errors %}
    <div class="alert alert-danger">
      {{ form.non_field_errors }}
    </div>
  {% endif %}
  {{ form.as_p }}
  <button type="submit">Submit</button>
</form>

Discussion

  • Be the first to comment on this lesson.