Menu
CoddyTech

Drawing a Form

Part of the Forms section of Coddy's Django journey. Lesson 6 of 20.

The page at /events/new/ writes every label and input by hand, and EventForm lists the same fields again. A form can draw itself: pass one to the template and write {{ form }} inside the <form> tag. A contact page:

<form method="post">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Send</button>
</form>

{{ form }} writes a label and an input for every field, in the order the class declares them. Each input gets the field's name and an id like id_email, so its label points at it. The form tag, the token and the button stay yours.

A form with nothing typed in it yet is the class called with no data: ContactForm(). Django also marks required inputs with required, so the browser stops an empty field before sending it.

challenge icon

Challenge

Easy
  • In new_event, pass an empty EventForm to the template as form.
  • In new_event.html, replace the labels and inputs with the form drawing itself. Keep the form tag, the token, the button and the error message.

Press Run and open /events/new/: Django draws the fields.

Try it yourself

{% extends "events/base.html" %}

{% block title %}Add an event{% endblock %}

{% block content %}
<h1>Add an event</h1>
{% if error %}
<p class="error">{{ error }}</p>
{% endif %}
<form method="post">
    {% csrf_token %}
    <label for="title">Title</label>
    <input id="title" name="title">
    <label for="date">Date</label>
    <input id="date" name="date" type="date">
    <label for="place">Place</label>
    <input id="place" name="place">
    <button type="submit">Add event</button>
</form>
{% endblock %}

All lessons in Forms

Practice on your own: Django playground