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 also protects every POST form. Another website could hide a form that posts to your site, and the visitor's browser would send it with their cookies. This attack is called cross-site request forgery, CSRF for short. 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
EasyIn events/templates/events/new_event.html, replace {# Write the form here #} with a form.
- Use
method="post"and put{% csrf_token %}first. Without it, Django refuses the form with 403. - Add a labelled input for
title,date(withtype="date") andplace, then a submit button.
Add an event, then press All events: it is in the list.
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 %}
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