Learn Django Β· 10/13

State and Memory: Sessions & Messages πŸͺ

8 min read

State and Memory: Sessions & Messages πŸͺ

In the world of web development, remembering who the user is and what they are doing is a fundamental requirement. From keeping users logged in, to retaining items in a shopping cart, to showing a simple "Settings Saved" notification, we rely on state and memory.

In this guide, we will explore how Django handles memory using Cookies, Sessions, and the Messages framework.


1. Understanding the Web's Statelessness πŸ€·β€β™‚οΈ

Definition:
Statelessness means that a system treats every request as an independent, isolated transaction. The HTTP protocol (the foundation of data communication on the World Wide Web) is inherently stateless.

The Problem:
Imagine you are running a fast-food drive-through. A customer drives up to the speaker and says, "I want a burger." You reply, "Okay." Then they drive to the next window and say, "And a large fries." Because you are entirely stateless, you stare at them blankly and say, "Who are you? What burger?"

Every time a user clicks a link, submits a form, or requests an image, their browser opens a connection to the server, asks for the resource, receives it, and closes the connection. A millisecond later, the server completely forgets the user ever existed.

If HTTP is stateless, how do we build things like multi-step checkout forms, persistent logins, or personalized dashboards? If the server forgets us instantly, how do we force it to remember?

The Solution:
We pass data back and forth with every single request to remind the server who we are. We achieve this using Cookies and Sessions.


2. Reading, Writing, and Securing Cookies πŸ₯ 

Definition:
A cookie is a small piece of data (maximum 4KB) that a server sends to the user's web browser. The browser stores it and automatically sends it back with every subsequent request to the same server.

The Problem:
If the server forgets the user after every request, we need a way to attach a "memory token" to the user so they can remind the server of their previous interactions.

How it works (The Scenario):
Imagine going to a nightclub. At the door, the bouncer checks your ID and stamps your hand. For the rest of the night, whenever you go to the bar, you do not need to show your passport; you just show the stamp. A cookie is your browser's hand stamp.

Writing Cookies in Django

In Django, you set a cookie on the HttpResponse object before returning it to the user.

python
from django.http import HttpResponse

def set_theme_cookie(request):
    # 1. Create the response object
    response = HttpResponse("Your theme is set to dark mode!")
    
    # 2. Set the cookie on the response
    response.set_cookie(
        key='theme', 
        value='dark',
        max_age=3600,       # Expires in 1 hour (in seconds)
        httponly=True,      # Prevents JavaScript from reading the cookie
        secure=True,        # Only sent over HTTPS
        samesite='Lax'      # Protects against Cross-Site Request Forgery (CSRF)
    )
    
    return response

πŸ›‘ Industry Standard: Securing Cookies

In the real world, you rarely set cookies without security flags. Malicious scripts (like XSS attacks) love to steal cookies. Always use:

  • httponly=True: Hides the cookie from client-side JavaScript (document.cookie).
  • secure=True: Ensures the cookie is only transmitted over encrypted HTTPS connections.
  • samesite='Lax' (or 'Strict'): Prevents the browser from sending this cookie along with cross-site requests.

Reading Cookies in Django

When the user makes their next request, the browser sends the cookie back. You can read it from the request.COOKIES dictionary.

python
def check_theme(request):
    # Use .get() to avoid KeyError if the cookie doesn't exist
    user_theme = request.COOKIES.get('theme', 'light') # Default to 'light'
    
    return HttpResponse(f"Your current theme is: {user_theme}")

Deleting Cookies

To remove a cookie, tell the browser to expire it immediately.

python
def reset_theme(request):
    response = HttpResponse("Theme reset to default.")
    response.delete_cookie('theme')
    return response

3. Session Management: Storing Temporary Data Behind the Scenes πŸ—„οΈ

Definition:
A session is a mechanism for storing user-specific data on the server-side, rather than on the client-side. The server generates a unique, random string (Session ID), stores the data in a database under that ID, and only sends the ID to the user's browser as a cookie.

The Problem:
Cookies are great, but they have severe limitations:

  1. Size limits: You can only store about 4KB of data in a cookie.
  2. Tampering: Users can open their browser's developer tools and change cookie values. If you set a cookie like is_admin=False, a user can easily change it to is_admin=True.

We cannot trust the client with sensitive data. We need a way to store data securely where the user cannot see or modify it.

How it works (The Solution):
Instead of giving the user their actual data, the server gives them a coat check ticket (the Session ID).
When the user returns, they hand the server the ticket. The server looks at the ticket, goes to the secure backroom (the Database), and retrieves the user's coat (the Data).

Under the Hood: Django's Session Setup

Before using sessions, ensure Django's session app and middleware are active. (These are enabled by default in a new Django 5.x project).

In settings.py:

python
INSTALLED_APPS = [
    # ...
    'django.contrib.sessions', # The database models for sessions
    # ...
]

MIDDLEWARE = [
    # ...
    'django.contrib.sessions.middleware.SessionMiddleware', # Intercepts requests/responses
    # ...
]

Reading and Writing Sessions

Django abstracts all the complex database lookups and cookie handling into a simple dictionary-like object: request.session.

python
def add_to_cart(request, item_id):
    # Writing to a session
    # If 'cart' doesn't exist in the session, initialize an empty list
    if 'cart' not in request.session:
        request.session['cart'] = []
        
    # Append the new item
    request.session['cart'].append(item_id)
    
    # Django automatically saves the session when you modify a top-level key.
    # But because we mutated a list INSIDE the dictionary, we must explicitly tell Django we modified it:
    request.session.modified = True 

    return HttpResponse("Item added to cart!")

def view_cart(request):
    # Reading from a session
    cart_items = request.session.get('cart', [])
    return HttpResponse(f"You have {len(cart_items)} items in your cart.")

πŸ›‘ Industry Standard: Clearing Sessions (Security)

When a user logs out, or when a security context changes (like a password reset), you should completely destroy the session. Do not just delete a single key; obliterate the entire session to prevent session hijacking.

python
def logout_user(request):
    # This deletes the session data from the database 
    # AND deletes the session cookie from the user's browser.
    request.session.flush()
    return HttpResponse("You have been securely logged out.")

4. The Messages Framework: Flash Notifications for Users ⚑

Definition:
The Messages framework is a tool for storing temporary, one-time notifications for the user. These messages are generated on one request and displayed to the user on the next request, after which they are automatically deleted.

The Problem:
Imagine a user fills out a "Change Password" form and clicks Submit. The server successfully updates the password. According to best practices (the Post/Redirect/Get pattern), the server should now redirect the user to a new page so they don't accidentally resubmit the form if they refresh.

But how do you tell the user "Password successfully changed!" on the next page?
You could add it to the URL (/profile/?success=true), but that is messy and easily bookmarked. You could manually write it to request.session, but then you have to write custom logic to remember to delete it after it is shown.

The Solution:
Django provides the messages framework. It uses sessions under the hood to store the message, and automatically handles cleaning it up once the template renders it.

Setup (Default in Django)

Ensure these are in your settings.py:

python
INSTALLED_APPS = [
    # ...
    'django.contrib.messages',
    # ...
]

MIDDLEWARE = [
    # ...
    'django.contrib.messages.middleware.MessageMiddleware',
    # ...
]

TEMPLATES = [
    {
        # ...
        'OPTIONS': {
            'context_processors': [
                # ...
                'django.contrib.messages.context_processors.messages', # Exposes 'messages' to templates
            ],
        },
    },
]

Adding Messages in Views

You can add messages with different urgency levels (tags) like debug, info, success, warning, and error.

python
from django.contrib import messages
from django.shortcuts import redirect

def update_profile(request):
    if request.method == 'POST':
        # ... logic to save profile ...
        
        # Add a success message
        messages.success(request, 'Your profile was updated successfully! πŸŽ‰')
        
        # Add a warning message just in case
        messages.warning(request, 'Please remember to verify your new email.')
        
        # Redirect to the profile view
        return redirect('profile_view')

Displaying Messages in Templates

Because of the messages context processor, a messages variable is automatically available in all your HTML templates.

You typically place this in your base.html layout file, right above your main content block, so notifications show up universally across your app.

html
<!-- base.html -->
{% if messages %}
    <ul class="message-container">
        <!-- Loop through the messages -->
        {% for message in messages %}
            <!-- message.tags will output the level (e.g., "success", "warning") -->
            <li class="alert alert-{{ message.tags }}">
                {{ message }}
            </li>
        {% endfor %}
    </ul>
{% endif %}

Fun fact: The moment you loop through messages in the template, Django silently deletes them from the session behind the scenes. If the user refreshes the page, the messages will be gone!


Summary

To build interactive, user-specific applications on a forgetful (stateless) protocol like HTTP, we rely on a layered memory system:

  1. Cookies: The foundational browser-side storage. Used to hold non-sensitive identifiers or preferences.
  2. Sessions: The secure server-side storage. Used to hold sensitive data (like shopping carts or user authentication state), linked to the user via a single, unguessable Session ID cookie.
  3. Messages: A high-level tool built on top of sessions, used specifically to flash one-time alerts to the user across page redirects.

References & Further Reading

Challenge

Your task is to implement a Django view function called update_user_profile that manages user preferences and session data based on the HTTP request method.

  1. Function Definition: The function must be named update_user_profile and accept a single HttpRequest object named request.

  2. POST Request Handling: If the request method is POST:

    • Create an HttpResponse object with the string content POST request processed.
    • Retrieve the value for the key theme from the request's POST data.
    • Set a cookie on the response named user_theme with the retrieved theme value. This cookie must be configured for security:
      • It must not be accessible to client-side JavaScript.
      • It must only be sent over a secure (HTTPS) connection.
      • It must have a samesite policy of 'Lax'.
      • It must expire in 30 days.
    • Update the user's session by setting a key named last_activity_token to the string value "active_user_token_xyz123".
    • Add a success-level flash message with the text "Profile updated successfully!".
    • Return the prepared HttpResponse object.
  3. GET Request Handling: If the request method is GET:

    • Create an HttpResponse object with the string content "Session cleared".
    • Completely clear all data from the user's current session.
    • Delete the user_theme cookie from the user's browser using the response object.
    • Return the HttpResponse object.

Expected result

The final code should be a single Python function, update_user_profile, that correctly implements the logic for both POST and GET requests.

  • The function should use an if/else block to check request.method == 'POST'.
  • Inside the POST block:
    • An HttpResponse object is instantiated, for example: response = HttpResponse('POST request processed').
    • The theme is retrieved, for example: theme = request.POST.get('theme').
    • response.set_cookie() is called with the key 'user_theme', the theme variable as the value, and all the required security flags: httponly=True, secure=True, and samesite='Lax'. The expiration should be set using max_age=2592000 or expires=datetime.now() + timedelta(days=30).
    • A session key is set using dictionary syntax: request.session['last_activity_token'] = 'active_user_token_xyz123'.
    • A success message is added via messages.success(request, 'Profile updated successfully!').
    • The response object is returned.
  • Inside the GET (or else) block:
    • An HttpResponse object is instantiated first to allow modification: response = HttpResponse('Session cleared').
    • The session is cleared by calling request.session.flush().
    • The cookie is deleted by calling response.delete_cookie('user_theme').
    • The response object is returned.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.