Main Content

Demonstration of a form using Django

Archive - Originally posted on "The Horse's Mouth" - 2012-03-04 21:57:17 - Graham Ellis

Our previous Django demonstrations have shown the setting up of the Django environment and data: [here]
Adding your own views and templating them: [here]
Separating the HTML from the Controller: [here]
Nesting Templates: [here]
and defining database table relationships: [here]

Let's now add a form definition and handling - which we're going to do as a separate template, view and URL (since our previous exercises were all involved in the display from databases rather than updating the databases).

1. Add URL to urls.py

  url(r'^team/formdemo.html?$', 'staff.views.formdemo'),

2. Add template (

  <html>
  <head>
  <title>This is a form demo</title>
  </head>
  <body bgcolor=#CCBBAA>
  <h1>Form Demo</h1>
  <b>{{ status }}</b><br /><br />
  <form method="POST">
  {% csrf_token %}
  {{ formholder.as_p }}
  <input type="submit" value="Submit" />
  </form>
  <hr />
  {{ saving }}
  </body>
  </html>


3. Add form class and controller to view.py

  from django.core.context_processors import csrf
  from django import forms
  
  class MyForm(forms.Form):
    role = forms.CharField(max_length=20)
    count = forms.IntegerField()
  
  def formdemo(request):
    havesubmission = "Blank form"
    stufftosave = ""
    if request.method == 'POST':
      form = MyForm(request.POST)
      if form.is_valid():
        havesubmission = "We HAVE got data to store"
        stufftosave = "Saving ... " + form.cleaned_data['role']
        stufftosave += ": " + str(form.cleaned_data['count'])
        form = MyForm()
      else:
        havesubmission = "Data Invalid - please correct"
    else:
      form = MyForm()
    mycontext = {'formholder': form, 'status': havesubmission, 'saving': stufftosave}
    mycontext.update(csrf(request))
    return render_to_response('staff/formdemo.html',mycontext)


Some notes:

The csrf_token is concerned with cross-site scripting attacks, making sure that the form was created by your server. You'll note that the token appears in the form, and Django will only accept a form submitted back with this element present

There are three code courses through the controller method:
a) The blank form ("unbound") when first submitted


b) The form that's partially filled in ("bound") together with error message to say it's wrong / incomplete, and why


c) The blank form again, but this time with an echo back of data that could be added to a database.


You'll note, once again, Django's "do not repeat yourself" approach. There's a lot going on under the hood (which you'll know if you've coded this sort of thing from scratch), but the methods and objects have been written by the Django team so that you don't have to.

There's a complete set of files showing the above code and changes in context [here] on our web site.