What are sessions?
When you're running a web application, you need to be able to enter data page by page on your way through, and have that data retained - on a shopping site, for example, you need to be able to add things into your basket page by page and have them stay there until you check out. But, alas, HTML / http are stateless protocols which don't retain your connection from page to page, and data will be lost unless you take specific action.
A
cookie can be sent as part of the response when you call up a web page, and that will then subsequently be sent back to the server as part of subsequent responses from the same browser to the same server. In essence, the cookie sent back is like an ID card saying "It's me again". And from that information, the server can look up the history of what's gone before.
"Don't Repeat Yourself" ... DRY. So many requirements want to store data from page to page that the Django
session classes and objects do all the hard work under the covers for you. The first time you visit a Django web site that uses this technology from your browser, a cookie is sent out with a unique value. That cookie is returned by the browser on each subsequent visit. And (the clever bit) anything that your view controller has stored within your request.session object is stored to a file or database at the end of each running of the controller script, and is read back at the start of the subsequent invocation. As there is a different session ID / database record / temporary file for each browser / user, this approach cleverly allows multple users to be running your application at the same time - with their data being cleanly passed on from page to page, but the data for the various different users being kept apart.
How do we turn on sessions in Django?
In Setting.py - check following (on 1.3.1 , they're turned on at installation by default)
* MIDDLEWARE to contain
'django.contrib.sessions.middleware.SessionMiddleware',
* INSTALLED_APPS to contain
'django.contrib.sessions',
If either is new, you'll need to add the database:
munchkin:training grahamellis$ python manage.py syncdb
Creating tables ...
Installing custom SQL ...
Installing indexes ...
No fixtures found.
munchkin:training grahamellis$
To the form demonstration in the previous section (
[here]), I've added a feature which stores the data that's been added by each user within their session. Here are the three extra lines of code which create a new member in the request.session 'dict' if necessary, and add the new information to it before storing it away again:
adding = request.session.get("newroles","")
adding += form.cleaned_data['role'] + " " + str(form.cleaned_data['count']) + "<br />"
request.session["newroles"] = adding
In order to make use of those in my demonstration, I have added the entire session contents back into the status report on the output - very much a training example to teach you what's happening:
myHistory = ""
for retained_key in request.session.keys():
myHistory += retained_key + " -> " + str(request.session[retained_key]) + "<br />"
havesubmission += "<br /><br />History ...<br />" + myHistory
Since I've added HTML tags into the report string (rather than making a lot of template changes), I've added the
|safe filter into the template:
<b>{{ status|safe }}</b><br /><br />
but you should note that this is a demonstration only which could leave me open to HTML / JavaScript injections.
Testing with multiple sessions at the same time

A good way to test that your sessions are working is to run your test webserver on a network IP address, which you can do from within manage.py. Here is such a run:
munchkin:training grahamellis$ python manage.py runserver 192.168.200.28:7777
Validating models...
0 errors found
Django version 1.3.1, using settings 'training.settings'
Development server is running at http://192.168.200.28:7777/
Quit the server with CONTROL-C.
[05/Mar/2012 09:44:28] "GET /team/ HTTP/1.1" 200 286
[05/Mar/2012 09:44:44] "GET /team/formdemo.html HTTP/1.1" 200 571
[05/Mar/2012 09:45:14] "POST /team/formdemo.html HTTP/1.1" 200 640
[05/Mar/2012 09:45:31] "POST /team/formdemo.html HTTP/1.1" 200 663
[05/Mar/2012 09:46:14] "GET /team/formdemo.html HTTP/1.1" 200 571
[05/Mar/2012 09:46:42] "POST /team/formdemo.html HTTP/1.1" 200 634
[05/Mar/2012 09:46:47] "POST /team/formdemo.html HTTP/1.1" 200 740

The illustration above shows one user session (which happens to be using Firefox). The illustrtation beside this paragraph shows a session that was live at the same time, and happens to be using Safari. You'll note that although it's the same application, the user data is completely different.
Sessions and cookies are very flexible - in this first example we used the default (database) storage medium, but we can also use plain text files and even memory based caching systems. The time that a session is to live when a user leaves the site is under configuration control, and you also need to ensure that you know what will happen in tidying up the database. Finally, you need to check that sessions are destroyed within the application where appropriate, to avoid users accidentally double ordering through incorrect use of the back button.
There's a complete set of files showing the above code and changes in context
[here] on our web site.
(written 2012-03-05, 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 [1745] Moodle, Drupal, Django (and Rails) - (2008-08-08)
[3136] A framework with python - Django - first steps - (2011-01-17)
[3138] Django - adding your own views, and then templating your views. - (2011-01-18)
[3139] Steering our Python courses towards wxPython, SQLite and Django - (2011-01-19)
[3140] Django - separating the HTML from the view / model - (2011-01-20)
[3624] Why do we need a Model, View, Controller architecture? - (2012-02-25)
[3633] Nesting Templates in Django - (2012-03-02)
[3634] Defining database relations in your Django model - (2012-03-02)
[3639] Demonstration of a form using Django - (2012-03-04)
[3698] How to stop forms on other sites submitting to your scripts - (2012-04-15)
[3705] Django Training Courses - UK - (2012-04-23)
[3919] What is a web framework? - (2012-11-10)
[4013] Web Frameworks - nested templates - (2013-02-22)
[4095] Django - first steps - Updated - (2013-05-19)
Some other Articles
The way of the Prioress - Melksham history pictured todayHotel food, Melksham - enjoy the variety of the American wayWiltshire Travel Times - Chippenham, Trowbridge, Salisbury and other places tooSwindon to Trowbridge - transport and travel optionsSessions (Shopping Carts) in Django - the Python Web FrameworkSorting dicts and arrays in TclApril, May and June 2012 - Public Open Source Programming CoursesBest tenner I ever spent?Parse error: parse error, unexpected T_STRING on brand new web site - why?