Django tip: How to set and get sessions?

/ #Django


Using sessions with Django is easy and it's something that you should know how to do as a developer.

Set up

Sessions comes built in with the standard Django setup. But it's always nice to just double check that "'django.contrib.sessions'," is in your list of INSTALLED_APPS in your settings.py file.

Setting sessions

In this little example, I will show you how to set a session.

def index(request):
    # String
    request.session['username'] = 'codewithstein'

    # Integers
    request.session['user_id'] = user.id

    # Booleans
    request.session['is_authenticated'] = True

    return render(request, 'index.html')

Great. Now we have a few session variables with strings, integers and boolean values.

Getting sessions

Getting sessions is also very easy.

def myaccount(request):
    # Check if "is_authenticated" is true. Default it to "False"
    if request.session.get('is_authenticated', False):
        print('You are authenticated')

    # Set username in a variable

    username = request.session.get('username', '')

    if username:
        print("Your username is %s" % username)
    
    return render(request, 'myaccount.html')

Deleting sessions

Now we know how to set and get sessions. But sometimes we want to delete them as well.

def logout(request):
    try:
        del request.session['is_authenticated']
    except KeyError:
        print("The key didn't exist")
    
    return redirect('index')

So now you know how to use sessions :-D

Comments

Calvin | Jul 17, 21 08:54

Short&sweet! Thanks for the tip!


Stein Ove Helset | Aug 05, 21 10:13

You’re welcome :-)

Cellou Cisse | Oct 18, 21 07:39

thanks for all.

Cellou Cisse | Oct 18, 21 07:43

Hello Mr stein!
I'm coding a blog website but I have difficulties to keep the "sidebar" working. Like your sidebar for this blog (search, categories...).
So, I would like you to help me please.

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.