How to Get and Set Session Data in Django

Django sessions are a great way of storing some information about a user server-side where storing it front-end is not appropriate from a security standpoint.

 

In this tutorial, we will learn how to set custom session data properties and get their values in Django.

 

Set Django Session Data

To set a new session data property, use request.session['prop_name'] and assign it a value using the Python = (assignment) operator.

 

item = request.session['prop_name'] = True

 

Get Django Session Data

Use request.session.get('prop_name') to get the value of a session property. Assign the result to a variable if you need to use it more than once.

 

item = request.session.get('prop_name')

 

Note – If there is no session property with the given name, None will be returned. This is useful as you can evaluate a session property even if it isn't set before assigning it a value.

 

Get and Set Session Full Example

The example below demonstrates how we could handle toggling between a dark theme in Django.

 

def theme(request):

  if request.method == 'POST':
    if request.session.get('dark_mode'):
      mode = request.session['dark_mode'] = False
    else:
      mode = request.session['dark_mode'] = True

    output = {
      'type': 'success',
      'mode': mode
    }
      
    return JsonResponse(output)

 

The idea here is we evaluate if the session data for dark_mode is not False or None and set it to False, else, set it to True.

django