Sessions in Django

1. Reference

http://docs.djangoproject.com/en/1.2/topics/http/sessions/

2. Configuration

2.1. Minimum common setup

To use sessions, at the very minimum, put the following in settings.py, and then use ONE of the following stores - database, cache or filesystem, as explained in the following subsections.

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware', # <-- This is the line required. The previous line is to show
                                                            #     that this needs to be just after CommonMiddleware
                                                            #     because order matters for this settings variable.
    ...

2.2. Database backed sessions

Store data for each session as a row in a table in the database.

In settings.py:

INSTALLED_APPS = (
    ...
    'django.contrib.sessions', # This is needed as the database Model for storing
                               # sessions is in this app
                               # After enabling, you require a './manage.py syncdb' 
                               # to actually create the database table
    ...

Default session store engine is database. That is why we need not mention the SESSION_ENGINE variable.

>>> from django.conf import settings
>>> print settings.SESSION_ENGINE
django.contrib.sessions.backends.db

2.3. Filesystem backed sessions

Store data for each session as a file in the filesystem.

In settings.py:

SESSION_ENGINE = 'django.contrib.sessions.backends.file'

#Optional. If you want to store temporary django sessions files to somewhere else
# By default they are stored in tempfile.gettempdir()
SESSION_FILE_PATH = os.path.join(tempfile.gettempdir(),'django_sessions')

2.4. Cache backed sessions

Store data for each session as a key-value pair in the cache.

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

# For persistent, cached data, set SESSION_ENGINE to "django.contrib.sessions.backends.cached_db"
# More info in docs.

3. Usage

3.1. Regular Usage

Just use request.session dictionary-like object in the views.

def mail_view( request ):
    from_name = request.session.get('from_name', None)
    
    defaults = {}
    if from_name:
        defaults['from_name'] = from_name

    if request.method == 'POST':
        form = MailForm(request.POST)
        if form.is_valid():
            request.session['from_name'] = form.cleaned_data['from_name'] # Save/cache user input to reuse later
        ...
    else:
        form = MailForm(initial=defaults) # Use the session data to pre-populate form

    ...

3.2. Clear out session

Useful in logout kind of situations.

  # In the view
  request.session.flush()

Two step procedure:

  1. Use request.session.set_test_cookie() to set a test cookie on the client browser before sending back the response.

  2. In the second page, use request.session.test_cookie_worked() to determine if cookies are enabled.

    1. If cookies are enabled, use request.session.delete_test_cookie() to cleanup.

See official example.

Django/Sessions (last edited 2010-09-12 18:39:06 by SandipBhattacharya)