Menu
CoddyTech

A POST Form

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

The page /events/new/ and its view are ready, but the page has no form to add an event. A form that changes data uses method="post": the browser sends the fields in the body of the request, not in the URL. The view reads them from request.POST, keyed by each input's name.

Django adds one rule. Another website could hide a form that posts to your site, and the visitor's browser would send it with their cookies: an attack called CSRF. So Django refuses any POST without a secret token from your own page, with 403 Forbidden. {% csrf_token %} inside the form writes that token. A newsletter form:

<form method="post">
    {% csrf_token %}
    <label for="email">Email</label>
    <input id="email" name="email" type="email">
    <button type="submit">Subscribe</button>
</form>

A <label> names the input whose id matches its for, and type="date" draws a calendar.

challenge icon

Challenge

Easy

In new_event.html, write the form the view expects:

  • It sends its fields with POST and carries the CSRF token.
  • One input, with a label, for each value the view reads. The date input draws a calendar.
  • A submit button.

Press Run, add an event, then open the home page.

Try it yourself

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

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

{% block content %}
<h1>Add an event</h1>
{# Write the form here #}
{% endblock %}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Forms

Practice on your own: Django playground