0
0
Djangoframework~5 mins

Why sessions matter in Django

Choose your learning style9 modes available
Introduction

Sessions help websites remember who you are as you move around. They keep your information safe and make your experience smooth.

When a user logs into a website and you want to keep them logged in as they browse.
When you want to save items in a shopping cart before checkout.
When you need to remember user preferences like language or theme.
When you want to track user activity without asking them to log in again.
When you want to protect sensitive data by storing it securely on the server.
Syntax
Django
request.session['key'] = 'value'
value = request.session.get('key', 'default')
del request.session['key']
Sessions store data on the server, not in the user's browser, making it safer.
You access session data through the request object in Django views.
Examples
Save the username 'alice' in the session to remember the user.
Django
request.session['username'] = 'alice'
Get the shopping cart from the session or start with an empty list if none exists.
Django
cart = request.session.get('cart', [])
Remove the username from the session, for example when the user logs out.
Django
del request.session['username']
Sample Program

This Django view counts how many times a user visits the page by saving a number in the session. Each time the page loads, it increases the count and shows it.

Django
from django.http import HttpResponse

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

Sessions rely on cookies to link the user to their stored data.

Session data is stored on the server, so it is more secure than storing data in the browser.

Always clear session data when it is no longer needed to keep things tidy.

Summary

Sessions let websites remember users and their data safely.

They are useful for login, carts, preferences, and tracking.

Django makes sessions easy to use with simple syntax.