All notes


Django handles three distinct parts of the work involved in forms:

In a similar way that a model class’s fields map to database fields, a form class’s fields map to HTML form "input" elements.

A form’s fields are themselves classes; they manage form data and perform validation when a form is submitted.

The Form class

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

The whole form, when rendered for the first time, will look like:

<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100">

Note that it does not include the "form" tags, or a submit button.


A Form instance has an is_valid() method, which runs validation routines for all its fields. When this method is called, if all fields contain valid data, it will:


We call the form’s is_valid() method; if it’s not True, we go back to the template with the form. This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required.

from django.shortcuts import render
from django.http import HttpResponseRedirect

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
        form = NameForm()

    return render(request, 'name.html', {'form': form})


<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />

Bound and unbound form instances

The distinction between Bound and unbound forms is important:

The form’s is_bound attribute will tell you whether a form has data bound to it or not.


The output options:

By default, {{form}} will render only the <label>/<input> pairs.
{{ form.as_table }} will render the pairs as table cells wrapped in <tr> tags.
{{ form.as_p }} will render the pairs wrapped in <p> tags.
{{ form.as_ul }} will render the pairs wrapped in <li> tags.
Note that you’ll have to provide the surrounding or