Session Framework in Django

The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID – not the data itself (unless you’re using the cookie based backend).

By default Django stores session in your database and hence it is mandatory to makemigrations and migrate in session. It will create required session.

The Django session framework is entirely, and solely cookie based on:

  • django.contrib.sessions.middleware.SessionMiddleware
  • django.contrib.sessions

Coding the app

As usual, we need to deal with some sessions. So, we need to create the app and create it according to the following tree.

  • To do so, look for the file urls.py in your app folder and add the code below:
from django.contrib import admin
from django.urls import path
from student import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('set/',views.setsession),
    path('get/',views.getsession),
    path('del/', views.delsession),
]

Set Session

  • Syntax:
    request.session['key'] = 'value'
    
  • Where the key is the name of the session and value is the value set to the session.
  • Now, let’s try to code the setsession.html code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Set Session</title>
</head>
<body>
    <h4>Session Set!!!!</h4>
</body>
</html>
  • The following code is used to set the cookie in views.py which by default sets the expiry date after 2 weeks
def setsession(request):
    request.session['name'] = 'Bipasha'
    return render(request,'student/setsession.html')
  • The output will be

  • Hence, the session in our system will show as follows:

  • On checking the backend i.e. Sqlite we will get something like this:

 

  • It is still empty because we have’nt used the getcookie yet.

Get Session

  • Syntax:
returned_value = request.session['key']
returned_value = request.session.get('key',default='None')
  • Where the key is the name of the session.
  • Now, let’s try to code the getsession.html code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Get Session</title>
</head>
<body>
    <h4>Get Session</h4>
    {{name}}
  
</body>
</html>
  • The views.py will be as follows:
def getsession(request):
    name = request.session['name']
    return render(request,'student/getsession.html',{'name':name})
  • The output will be:

  • You will see the following changes in Sqlite database:

  • To add an session to the existing session the getsession.html code will be:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Get Session</title>
</head>
<body>
    <h4>Get Session</h4>
    {{name}}
    {{lname}}
</body>
</html>
  • Make the folowing changes in views.py
def setsession(request):
    request.session['name'] = 'Bipasha'
    request.session['lname'] = 'Codedec'
    return render(request,'student/setsession.html')


def getsession(request):
    name = request.session.get('name')
    lname = request.session.get('lname')
    return render(request,'student/getsession.html',{'name':name,'lname':lname})
  • The output will be:

  • You will see the following changes in Sqlite database:

Delete Session

  • Syntax:
del request.session['key']
  • The views.py for delete session is:
def delsession(request):
    if 'name' in request.session:
        del request.session['name']
    return render(request,'student/delsession.html')
  • Hence, the delsession.html is:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Delete Session</title>
</head>
<body>
    <h4>Session Deleted!!</h4>

</body>
</html>
  • If you run the server it will raises OperationalError if the given key isnt already set in the session

  • So, set the session and then run the server/del/

 

Setting Expiration Time for Session

  • SESSION_COOKIE_AGE : This variable is used to set cookie expiration time in seconds. By default, it is set to 1209600 seconds or 2 weeks. If SESSION_EXPIRE_AT_BROWSER_CLOSE is not set then Django uses this variable to set cookie expiration time. Here is how you can set session cookie expiration time to 5 days: SESSION_COOKIE_AGE = 3600*24*5
  • SESSION_EXPIRE_AT_BROWSER_CLOSE : This variable controls whether to expire the session cookie when the user closes the browser. By default, it is set to False. If set to True, session cookie lasts until the browser is closed, irrespective of the value of SESSION_COOKIE_AGE.