Django session

Django session is a way to store information about a user across multiple requests. This enables you to manage user-specific data, such as login status, preferences, or shopping cart contents, without requiring the user to authenticate or pass data on every request.

How Django Sessions Work?

1. Session ID: Django generates a unique session ID for each user, stored in a cookie on the client’s browser.

2. Session Data: The actual session data is stored on the server (e.g., database, file system, or cache).

3. Session Persistence: The session ID in the client’s cookie links to the data on the server, enabling persistence across multiple requests.

How to Enable Sessions in Django

Django sessions are enabled by default. Ensure the following middleware is added to your MIDDLEWARE setting in settings.py:


MIDDLEWARE = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
]

Also, ensure ‘django.contrib.sessions’ is in INSTALLED_APPS.

Using Sessions in Django

1. Set Session Data

Store data in the session using the request.session dictionary:


def set_session(request):
    request.session['username'] = 'John'
    request.session['user_id'] = 35
    return HttpResponse("Session data set!")

2. Get Session Data

Retrieve data from the session:


def get_session(request):
    username = request.session.get('username', 'Guest')  # Default to 'Guest' if not set
    return HttpResponse(f"Hello, {username}!")

3. Delete Session Data

Remove specific session data:


def delete_session(request):
    if 'username' in request.session:
        del request.session['username']
    return HttpResponse("Username removed from session.")

Example: Login System with Sessions


from django.http import HttpResponse, HttpResponseRedirect

def login(request):
    # Simulate user authentication
    username = request.POST.get('username')
    if username == "admin":
        request.session['is_logged_in'] = True
        request.session['username'] = username
        return HttpResponseRedirect('/dashboard/')
    return HttpResponse("Invalid login.")

def dashboard(request):
    if request.session.get('is_logged_in', False):
        username = request.session.get('username')
        return HttpResponse(f"Welcome, {username}!")
    return HttpResponseRedirect('/login/')

def logout(request):
    request.session.flush()  # Clear all session data
    return HttpResponse("Logged out.")