Lesson 48 of 60 – Django Sessions
80%

Django Sessions

A session allows Django to remember information about a user between different requests. Sessions are commonly used for login systems, shopping carts, temporary preferences, and other user-specific data.

HTTP requests are independent by default. Django sessions provide a way to maintain state across multiple requests.

Note: Django sessions are commonly used together with authentication. After a successful login, Django uses session data to remember the authenticated user across requests.

1. What is a Session?

A session is a mechanism for storing information that belongs to a particular user's interaction with a website.

For example, a website can remember:

  • Whether a user is logged in.
  • A shopping cart.
  • Temporary preferences.
  • Recently selected options.

2. Why Do We Need Sessions?

HTTP is stateless. Each request is normally independent from previous requests.

Sessions allow an application to maintain information across requests.

Request 1
   ↓
Store Session Data
   ↓
Request 2
   ↓
Read Session Data
   ↓
Request 3
   ↓
Read/Update Session Data

3. Django Session Framework

Django provides a built-in session framework through django.contrib.sessions.

A new Django project normally includes the session application in INSTALLED_APPS.

INSTALLED_APPS = [

    "django.contrib.sessions",

]

4. Session Middleware

Django uses session middleware to make session information available to requests.

MIDDLEWARE = [

    "django.middleware.security.SecurityMiddleware",

    "django.contrib.sessions.middleware.SessionMiddleware",

    "django.middleware.common.CommonMiddleware",

]

The session middleware makes request.session available in views.

5. Running Session Migrations

Django's default database-backed session system requires its database table to be created.

python manage.py migrate

After migration, Django can store session information using the configured session backend.

6. request.session

Django provides session data through request.session.

def home(request):

    request.session["username"] = "Rahul"

    return render(
        request,
        "home.html"
    )

The session behaves similarly to a dictionary.

7. Setting Session Data

Use a key and value to store data in the session.

request.session["username"] = "Rahul"

Another example:

request.session["course"] = "Python"

The data can be accessed in later requests while the session remains available.

8. Reading Session Data

Read a session value by using its key.

username = request.session["username"]

You can also use get() to provide a default value.

username = request.session.get(
    "username",
    "Guest"
)

9. Session get() Method

The get() method is useful when a session key may not exist.

course = request.session.get(
    "course",
    "No Course Selected"
)

This avoids directly accessing a missing key.

10. Updating Session Data

A session value can be changed by assigning a new value to the same key.

request.session["course"] = "Django"

If the key already exists, its value is updated.

11. Deleting Session Data

Use del to remove a specific session key.

del request.session["course"]

Make sure the key exists before deleting it or handle the case where it does not exist.

12. Checking Whether a Session Key Exists

The in operator can be used to check whether a session key exists.

if "username" in request.session:

    print("Username exists")

This is useful before reading or deleting optional session data.

13. Clearing Session Data

Django provides flush() to clear the current session data and create a new session key.

request.session.flush()

This is different from simply deleting one session key.

14. Session clear() Method

The clear() method removes all data from the session while keeping the session available.

request.session.clear()

Use it when you want to remove stored session data without using the same operation as flush().

15. Session Keys

Django sessions store values using keys.

request.session["name"] = "Rahul"
request.session["age"] = 25
request.session["city"] = "Patna"

Each key identifies a particular piece of session data.

16. Storing Login Information

Sessions are commonly used to maintain login state.

Django's authentication framework handles the authentication session when you use:

login(request, user)

After login, later requests can access the authenticated user through request.user.

17. Session and request.user

Django authentication and sessions work together.

if request.user.is_authenticated:

    print(
        request.user.username
    )

The authentication middleware uses session information to associate the request with the logged-in user.

18. Session Expiry

Django sessions can have an expiry time.

You can configure the session age using:

SESSION_COOKIE_AGE = 1209600

The value is measured in seconds. The default session age in Django is commonly two weeks.

19. Expiring Session on Browser Close

You can configure Django to expire the session cookie when the browser is closed.

SESSION_EXPIRE_AT_BROWSER_CLOSE = True

This controls the browser cookie behavior and should be considered as part of the application's session policy.

20. Session Cookie

Django commonly uses a session cookie in the user's browser to identify the current session.

The cookie name can be configured using:

SESSION_COOKIE_NAME = "sessionid"

The default cookie name is commonly sessionid.

21. Session Backend

Django supports different session storage backends.

One common backend stores session data in the database:

django.contrib.sessions.backends.db

Other supported approaches can store session data in cached storage, cookies, or files depending on the configured backend.

22. Database Session Backend

The database session backend stores session information in the database.

SESSION_ENGINE =
"django.contrib.sessions.backends.db"

The session table is created through Django migrations.

python manage.py migrate

23. Using Sessions for a Shopping Cart

Sessions can be used to store temporary shopping-cart information.

request.session["cart"] = [
    101,
    102,
    103
]

Later, the application can read the stored product identifiers.

cart = request.session.get(
    "cart",
    []
)

24. Updating Mutable Session Data

When modifying mutable objects such as dictionaries or lists stored in a session, you may need to mark the session as modified.

request.session["cart"] = []

request.session["cart"].append(101)

request.session.modified = True

Alternatively, assigning the modified value back to the session key makes the change explicit.

25. Session Security Settings

Django provides settings that can improve session-cookie security.

SESSION_COOKIE_SECURE = True

SESSION_COOKIE_HTTPONLY = True

SESSION_COOKIE_SAMESITE = "Lax"

When deploying over HTTPS, SESSION_COOKIE_SECURE helps ensure the session cookie is sent only over secure connections.

26. Common Session Mistakes

  • Forgetting to enable session middleware.
  • Forgetting the sessions application.
  • Not running migrations for database-backed sessions.
  • Using session keys inconsistently.
  • Trying to read a missing session key directly.
  • Storing unnecessarily large amounts of data in sessions.
  • Forgetting to mark a modified mutable session object as changed when needed.
  • Using insecure cookie settings in production.

27. Session Security Practices

  • Use HTTPS in production.
  • Use secure session-cookie settings.
  • Do not store sensitive information unnecessarily in sessions.
  • Keep session data reasonably small.
  • Use Django's built-in session framework.
  • Use appropriate session expiry settings.
  • Protect authentication-related pages and actions.

28. Complete Session Workflow

User Sends Request
        ↓
Django Session Middleware
        ↓
Read Session Information
        ↓
request.session
        ↓
Read / Add / Update Data
        ↓
Response
        ↓
Session Information Saved
        ↓
Next Request Can Use It

29. Complete Session Example

views.py

from django.shortcuts import render

def set_session(request):

    request.session["username"] = "Rahul"

    return render(
        request,
        "session.html"
    )


def get_session(request):

    username = request.session.get(
        "username",
        "Guest"
    )

    return render(
        request,
        "session.html",
        {
            "username": username
        }
    )


def clear_session(request):

    request.session.clear()

    return render(
        request,
        "session.html"
    )

session.html

<h2>
Welcome {{ username }}
</h2>

30. Django Sessions Summary

Django sessions allow applications to maintain state across multiple HTTP requests.

  • Use request.session to access session data.
  • Store data using key-value pairs.
  • Use get() for optional session values.
  • Use del to remove individual session keys.
  • Use clear() to remove session data.
  • Use flush() to clear the session and create a new session key.
  • Django authentication uses sessions to maintain login state.
  • Session expiry can be configured.
  • Session cookies have configurable security settings.
  • Do not store unnecessary sensitive information in sessions.

📌 Key Points

  • Django sessions maintain information across requests.
  • request.session provides access to session data.
  • Session data is stored using key-value pairs.
  • request.session.get() safely reads optional data.
  • clear() removes session data.
  • flush() clears session data and creates a new session key.
  • Django authentication uses sessions to remember logged-in users.
  • Session expiry and cookie security can be configured in settings.py.
  • Database-backed sessions require migrations.

🧠 Quick Quiz

Question: Which Django object is used to access session data inside a view?