Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Session in Django

Tags:

django

session

So far the Documentation for Django has been too technical. How do I create a session and store variables in it or get variables from it? I'm new to the Django framework, hence why the Documentation is too technical. Sessions are my 'last step'.

like image 326
Reznor Avatar asked Feb 19 '10 00:02

Reznor


People also ask

How do I create a user session in Django?

If you want to use a database-backed session, you need to add 'django. contrib. sessions' to your INSTALLED_APPS setting. Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.

How does Django session work?

Django provides a session framework that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side. So the data itself is not stored client side.

How long does Django session last?

As you mentioned in your question, sessions in Django live for as long as SESSION_COOKIE_AGE determines (which defaults to 2 weeks) from the last time it was "accessed". Two exceptions for that: you can set an expiry time to a session yourself, and then it depends on that.


1 Answers

Assuming you want database based sessions (Django also offers file based sessions, and cache based sessions):

  1. Open settings.py and find MIDDLEWARE_CLASSES. Add 'django.contrib.sessions.middleware.SessionMiddleware' to the list.
  2. Find INSTALLED_APPS in the same file and add 'django.contrib.sessions' there.
  3. Run manage.py syncdb from the command line.

After the initial setup you can use request.session in your views to store information between requests.

For example this will store the information:

request.session['name'] = 'Ludwik'

and you can retrieve it as easly:

print request.session['name']

or

if request.session['name'] == 'Ludwik':
   print 'you are awesome!'

For other things you can do with the request.session object see the documentation.

like image 153
Ludwik Trammer Avatar answered Oct 22 '22 06:10

Ludwik Trammer