[Django]-How to set and get session in Django?

101👍

For setting session variable:

request.session['idempresa'] = profile.idempresa

For getting session Data:

if 'idempresa' in request.session:
    idempresa = request.session['idempresa']

65👍

For setting session variable:

request.session['fav_color'] = 'blue'

For getting session Data

fav_color = request.session.get('fav_color', 'red')

Reference: https://docs.djangoproject.com/en/dev/topics/http/sessions/

👤Arun

2👍

You can set and get session with request.session['key'] and get session with request.session.get(‘key’) in Djanog Views as shown below. *request.session.get() returns None by default if the key doesn’t exist and you can change None to other value like Doesn't exist by setting it to the 2nd argument as shown below and you can see When sessions are saved and you can see my question and my answer explaining when and where session is saved:

# "views.py"

from django.shortcuts import render

def test(request):
    request.session['person'] = {'name':'John','age':27}
    print(request.session['person']) # {'name':'John','age':27}
    print(request.session['person']['name']) # John
    print(request.session['person']['age']) # 27
    print(request.session.get('person')) # {'name':'John','age':27}
    print(request.session.get('person')['name']) # John
    print(request.session.get('person')['age']) # 27
    print(request.session.get('animal')) # None
    print(request.session.get('animal', "Doesn't exist")) # Doesn't exist
    return render(request, 'index.html', {})

And, you can get session with request.session.key in Django Templates as shown below:

# "templates/index.html"

{{ request.session.person }}      {# {'name':'John','age':27} #}
{{ request.session.person.name }} {# John #}
{{ request.session.person.age }}  {# 27 #}

And, you can delete session with the code below. *request.session.pop(‘key’) can get, then delete session and error occurs if the key doesn’t exist and the 2nd argument is not set and if the key doesn’t exist and the 2nd argument is set, the 2nd argument is returned and request.session.clear() and request.session.flush() can delete all the current session and you can see my question and the answer explaining the difference between request.session.clear() and request.session.flush():

# "views.py"

from django.shortcuts import render

def test(request):
    del request.session['person']
    del request.session['person']['name']
    del request.session['person']['age']
    print(request.session.pop('person')) # {'name':'John','age':27}
    print(request.session.pop('animal') # Error
    print(request.session.pop('animal', "Doesn't exist")) # Doesn't exist
    request.session.clear()
    request.session.flush()
    return render(request, 'index.html', {})

Leave a comment