Skip to content

django

Introduction

I started this halfway, so restart when done to finish the start !!

Source : visit

working with forms

Source : visit

GET and POST are the only HTTP methods to use when dealing with forms.

The Form class maps fields to form elements, like Model maps fields to database entries/columns. And a ModelForm can be used to map an existing Model int a Form.

A Form's Fields are also themselves classes, like FileField or DateField. They are represented in html as Widget classes, who can be overridden if needed.

You generally instantiate a model class, and create a view using a template:

form class

instantiate a subclass of forms.Form, and add field to it or let django do that (ModelForm)

forms
1
2
3
4
5
# forms.py
from django import forms

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

view

views
# views.py

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

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
    else:
        form = NameForm()

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

template

The rendered form does not contain

tags, so you provide more or less this in name.html

templates
1
2
3
4
5
<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

bound vs unbound

bound forms have data attached, either manually or from a previous submit. Unbound forms show up empty.

You can use .is_bound to show.

cleaned_data

Data that has been filled in and checked for validity appears in a dictionary in form.cleaned_data. For instance (views.py) :

form validation
1
2
3
4
if form.is_valid():
    subject = form.cleaned_data['subject']
    message = form.cleaned_data['message']
    ...

file fields

File fields do not show up in cleaned_data, but in request.FILES rather then request.POST. Binding files will be described later.

form rendering options

You can render the form with {{ form }} but it has some other options as well:

  • {{ form.as_table }} will render them as table cells wrapped in tags
  • {{ form.as_p }} will render them wrapped in

    tags

  • {{ form.as_ul }} will render them wrapped in
  • tags

rendering yourself

Also possible and sometimes needed, you can access the fields by their names :

fields
{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.subject.errors }}
    <label for="{{ form.subject.id_for_label }}">Email subject:</label>
    {{ form.subject }}
</div>
<div class="fieldWrapper">
    {{ form.message.errors }}
    {{ form.message.label_tag }}
    {{ form.message }}
</div>

There are also convenience shortcuts like the second div, it generates the complete label like the verbose version in the first div.

The form.non_field_errors tag displays a list of form errors where normally the {{ form }} would have done it.