Home Accessibility Courses Diary The Mouth Facebook Resources Site Map About Us Contact
Demonstration of a form using Django

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:
New form in Djangoa) The blank form ("unbound") when first submitted


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


Form successfully submitted - Djangoc) 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.
(written 2012-03-04, updated 2012-03-10)

 
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
Y306 - Python - The Django web framework
  [4095] Django - first steps - Updated - (2013-05-19)
  [4013] Web Frameworks - nested templates - (2013-02-22)
  [3919] What is a web framework? - (2012-11-10)
  [3705] Django Training Courses - UK - (2012-04-23)
  [3698] How to stop forms on other sites submitting to your scripts - (2012-04-15)
  [3640] Sessions (Shopping Carts) in Django - the Python Web Framework - (2012-03-05)
  [3634] Defining database relations in your Django model - (2012-03-02)
  [3633] Nesting Templates in Django - (2012-03-02)
  [3624] Why do we need a Model, View, Controller architecture? - (2012-02-25)
  [3140] Django - separating the HTML from the view / model - (2011-01-20)
  [3139] Steering our Python courses towards wxPython, SQLite and Django - (2011-01-19)
  [3138] Django - adding your own views, and then templating your views. - (2011-01-18)
  [3136] A framework with python - Django - first steps - (2011-01-17)
  [1745] Moodle, Drupal, Django (and Rails) - (2008-08-08)


Back to
Sorting dicts and arrays in Tcl
Previous and next
or
Horse's mouth home
Forward to
Sessions (Shopping Carts) in Django - the Python Web Framework
Some other Articles
Hotel food, Melksham - enjoy the variety of the American way
Wiltshire Travel Times - Chippenham, Trowbridge, Salisbury and other places too
Swindon to Trowbridge - transport and travel options
Demonstration of a form using Django
Sorting dicts and arrays in Tcl
April, May and June 2012 - Public Open Source Programming Courses
Best tenner I ever spent?
Parse error: parse error, unexpected T_STRING on brand new web site - why?
4253 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3639_Dem ... jango.html • PAGE BUILT: Sun Mar 30 15:20:58 2014 • BUILD SYSTEM: WomanWithCat