0
0
Djangoframework~5 mins

Setting and getting session data in Django

Choose your learning style9 modes available
Introduction

Sessions help remember information about a user while they browse your website. This makes the site feel personal and keeps data safe between pages.

Remembering a user's login status after they sign in.
Storing items in a shopping cart while the user shops.
Keeping track of user preferences like language or theme.
Saving temporary data during a multi-step form process.
Tracking user visits or actions for analytics.
Syntax
Django
request.session['key'] = value  # To set data
value = request.session.get('key', default)  # To get data
Session data is stored on the server, not in the user's browser.
Use get to avoid errors if the key does not exist.
Examples
Stores the username 'alice' in the session under the key 'username'.
Django
request.session['username'] = 'alice'
Retrieves the shopping cart list from the session, or an empty list if it doesn't exist yet.
Django
cart = request.session.get('cart', [])
Saves the user's theme preference as 'dark'.
Django
request.session['theme'] = 'dark'
Counts how many times the user has visited by getting the current count and adding one.
Django
visits = request.session.get('visits', 0)
request.session['visits'] = visits + 1
Sample Program

This Django view counts how many times a user visits the page. It gets the current count from the session, adds one, saves it back, and shows the count.

Django
from django.http import HttpResponse

def visit_counter(request):
    visits = request.session.get('visits', 0)
    visits += 1
    request.session['visits'] = visits
    return HttpResponse(f"You have visited this page {visits} times.")
OutputSuccess
Important Notes

Session data is stored per user and lasts until the session expires or is cleared.

Always check if a session key exists before using it to avoid errors.

Sessions use cookies to identify users but do not store the actual data in cookies.

Summary

Sessions let you save and retrieve user-specific data across pages.

Use request.session['key'] = value to save data.

Use request.session.get('key', default) to safely get data.