Examples


Django Session


What is Session in Django?

A session is a way to store information about a specific user across multiple requests (pages) in a web application. This info is stored on the server, and the client (browser) just holds a session ID in a cookie.

Django Session

Why We Use Sessions?

Sessions solve a key problem: HTTP is stateless, meaning every request is independent and doesn't remember who made it. But in most web apps, we need to:

  • Keep a user logged in
  • Remember a user's preferences
  • Store a shopping cart
  • Track activity or progress

File and Folder Structure

Django Session File and Folder Structure

1. Create the Views

myapp/views.py

This Django view file handles session-based user interaction. It sets, displays, and clears a username stored in the session, with redirection between pages based on user actions.

from django.shortcuts import render, redirect

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        request.session['username'] = username
        return redirect('home')
    return render(request, 'index.html')

def home(request):
    username = request.session.get('username', 'Guest')
    return render(request, 'home.html', {'username': username})

def logout(request):
    request.session.flush()
    return redirect('login')

2. Create Templates

myapp/templates/index.html

This HTML template provides a form to input a username and submit it via POST. The submitted data is saved to the session using the set_session view.

<html>
    <head>
        <title>Login</title>
    </head>
    <body>
        <form method="post" action="{% url 'login' %}">
            {% csrf_token %}
            <label>Enter Name</label><br>
            <input type="text" name="username" required><br><br>
            <input type="submit" value="Login">
        </form>
    </body>
</html>
myapp/templates/home.html

This HTML template displays a welcome message using the session-stored username. It also provides a logout link that clears the session when clicked.

<html>
    <head>
        <title>Home</title>
    </head>
    <body>
        <h2>Welcome, {{ username }}!</h2>
        <p><a href="{% url 'logout' %}">Clear Session (Logout)</a></p>
    </body>
</html>
myapp/urls.py

This Django urls.py file maps URL paths to their corresponding view functions. It handles routes for setting, showing, and clearing session data, along with the home page.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.login, name='login'),      
    path('home/', views.home, name='home'),
    path('logout/', views.logout, name='logout'),
]

Output

Set Session

This page allows the user to enter a username through a form. On submission, the username is stored in the Django session.

django Session set session

Show Session

This page displays the username stored in the session. It confirms that the session data was saved and retrieved successfully.

django Session show session