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.
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:
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
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",
]
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.
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.
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.
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.
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"
)
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.
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.
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.
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.
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.
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().
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.
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.
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.
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.
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.
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.
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.
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
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",
[]
)
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.
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.
User Sends Request
↓
Django Session Middleware
↓
Read Session Information
↓
request.session
↓
Read / Add / Update Data
↓
Response
↓
Session Information Saved
↓
Next Request Can Use It
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>
Django sessions allow applications to maintain state across multiple HTTP requests.
request.session to access session data.get() for optional session values.del to remove individual session keys.clear() to remove session data.flush() to clear the session and create a new session key.request.session provides access to session data.request.session.get() safely reads optional data.clear() removes session data.flush() clears session data and creates a new session key.settings.py.Question: Which Django object is used to access session data inside a view?