Django's session framework is provided in two pieces—a middleware application and a Django model. Middleware applications are applications that run between the Django framework and your own custom website code. The session framework should be enabled by default. However, we will cover the steps to enable it anyway.
To enable the session framework, you need to modify the MIDDLEWARE_CLASSES setting in the settings.py file to include the following class:
'django.contrib.sessions.middleware.SessionMiddleware',
You also need to add the following model to the INSTALLED_APPS setting in the settings.py file:
'django.contrib.sessions',
Watch Out!
If django.contrib.sessions wasn't already listed in the installed application, run the syncdb application to create the session table in the database.
Django stores session data in a table in the database by default. However, you can also configure the session manager to store the data in the file system or in cached memory. Storing session data in the file system or cache may improve site performance in some instances. To change the session backend, set the SESSION_ENGINE setting in the sessions.py file to one of the following:
django.contrib.sessions.backends.db
django.contrib.sessions.backends.file
django.contrib.sessions.backends.cache
Watch Out!
If you want to use the cache backend, be sure that you have configured your cache. Also, you should use the cache session backend only if you are using the memcached cache backend.
By the Way
If you decide to use the file backend for sessions, you can configure the location where the session data is stored by adding the SESSION_FILE_PATH setting to the settings.py file. The SESSION_FILE_PATH setting defaults to the /tmp directory.
You can use the following settings in the settings.py file to configure the session manager:
SESSION_COOKIE_AGE: The default is 1209600 (two weeks). Specifies the age of session cookies in seconds.
SESSION_COOKIE_DOMAIN: The default is None. Specifies the domain string to use for cross-domain cookies.
SESSION_COOKIE_NAME: The default is sessionid. Specifies the cookie name for sessions.
SESSION_COOKIE_SECURE: The default is False. If it's set to True, the cookie is marked as secure, and the browser should ensure that it will be sent only over an HTTPS connection.
SESSION_EXPIRE_AT_BROWSER_CLOSE: The default is False. If it's set to True, the session expires when the user closes the browser window.
SESSION_SAVE_EVERY_REQUEST: The default is False. If it's set to False, the session is saved only if the data actually changes. If it's set to True, the session is saved after every request.