Reznor
Reznor

Reputation: 1285

Create a Session in Django

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'.

Upvotes: 18

Views: 49922

Answers (2)

Ludwik Trammer
Ludwik Trammer

Reputation: 25052

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.

Upvotes: 37

user6932238
user6932238

Reputation:

MIDDLEWARE_CLASSES should have −

'django.contrib.sessions.middleware.SessionMiddleware'

INSTALLED_APPS should have −

'django.contrib.sessions'

Change our login view to save our username cookie server side −

def login(request):
  username = 'not logged in'

  if request.method == 'POST':
    MyLoginForm = LoginForm(request.POST)

    if MyLoginForm.is_valid():
       username = MyLoginForm.cleaned_data['username']
       request.session['username'] = username
    else:
        MyLoginForm = LoginForm()

  return render(request, 'loggedin.html', {"username" : username}

create formView view for the login form, where we won’t display the form if cookie is set −

def formView(request):
   if request.session.has_key('username'):
      username = request.session['username']
      return render(request, 'loggedin.html', {"username" : username})
   else:
      return render(request, 'login.html', {})

change the url.py file to change the url so it pairs with our new view −

from django.conf.urls import patterns, url
from django.views.generic import TemplateView

urlpatterns = patterns('myapp.views',
   url(r'^connection/','formView', name = 'loginform'),
   url(r'^login/', 'login', name = 'login'))
   url(r'^logout/', 'logout', name = 'logout'),

create a simple logout view that erases our cookie.

def logout(request):
   try:
      del request.session['username']
   except:
      pass
   return HttpResponse("<strong>You are logged out.</strong>")

Upvotes: 3

Related Questions