Sessions and Cookies

Back

Loading concept...

🍪 Django Sessions & Cookies: Your Website’s Memory

The Big Picture: Why Does Your Website Need Memory?

Imagine you walk into your favorite ice cream shop every day. The shopkeeper remembers your name, your favorite flavor, and that you always want extra sprinkles. That’s memory!

But websites are different. Every time you visit a page, the website forgets who you are. It’s like the shopkeeper has amnesia!

Sessions and Cookies are Django’s way of giving your website a memory. Let’s explore how they work!


🎯 Our Everyday Analogy: The Ice Cream Shop

Throughout this guide, we’ll use an ice cream shop to explain everything:

Real World Django Concept
Loyalty card with a number Cookie
Shop’s customer database Session
Your preferences stored Session data
Card expiry date Cookie/Session expiration

📚 Sessions Overview

What is a Session?

Think of a session as a special folder the ice cream shop keeps for each customer. When you walk in, they look up your folder and see:

  • Your name
  • Your favorite flavors
  • How many visits you’ve made
  • Any special deals you have

In Django terms: A session stores information about a visitor on the server side. It’s private, secure, and hidden from the visitor.

How Sessions Work

graph TD A["User visits website"] --> B["Django creates session"] B --> C["Session ID created"] C --> D["ID sent to browser as cookie"] D --> E["Browser stores cookie"] E --> F["Next visit: browser sends cookie"] F --> G["Django finds matching session"] G --> H["User recognized!"]

Session ID: Your Secret Ticket

When you first visit a Django website:

  1. Django creates a session (your folder)
  2. Django gives you a session ID (a secret code)
  3. This ID is stored in a tiny cookie in your browser
  4. Next time you visit, you show the ID
  5. Django finds your folder and remembers you!

Example: What a session ID looks like:

abc123xyz789def456

It’s just a random string. Nothing personal is stored in it!


⚙️ Session Configuration

Where Does Django Store Sessions?

Django can store sessions in different places. It’s like choosing where the ice cream shop keeps customer folders:

Storage Option Description Best For
Database Store in database tables Most websites
Cache Store in memory (fast!) High-traffic sites
File Store as files on server Simple setups
Signed Cookies Store in user’s browser Small data only

Setting Up Session Storage

In your settings.py, tell Django where to store sessions:

Database (Default):

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

Cache (Faster):

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

File-based:

SESSION_ENGINE = 'django.contrib.sessions.backends.file'

Important Session Settings

# How long should sessions last? (in seconds)
# 1209600 = 2 weeks
SESSION_COOKIE_AGE = 1209600

# Should session expire when browser closes?
SESSION_EXPIRE_AT_BROWSER_CLOSE = False

# Name of the session cookie
SESSION_COOKIE_NAME = 'sessionid'

# Only send cookie over HTTPS?
SESSION_COOKIE_SECURE = True

# Prevent JavaScript from reading cookie?
SESSION_COOKIE_HTTPONLY = True

Why These Settings Matter

Setting What It Does Ice Cream Shop Analogy
SESSION_COOKIE_AGE Session lifetime How long your loyalty card is valid
SESSION_EXPIRE_AT_BROWSER_CLOSE Delete when browser closes “Valid only during this visit”
SESSION_COOKIE_SECURE HTTPS only Only accept card at secure locations
SESSION_COOKIE_HTTPONLY No JavaScript access Card can’t be photocopied

đź”§ Session Data Operations

The Four Essential Operations

Working with sessions is like using a notebook. You can:

  1. Write something down
  2. Read what you wrote
  3. Erase something
  4. Check if something exists

Writing to Sessions (SET)

Store information in the user’s session:

def add_to_cart(request):
    # Save favorite flavor to session
    request.session['favorite'] = 'chocolate'

    # Save visit count
    request.session['visits'] = 5

    # Save a list
    request.session['cart'] = ['cone', 'sprinkles']

Reading from Sessions (GET)

Retrieve stored information:

def show_preferences(request):
    # Get with a default value
    flavor = request.session.get('favorite', 'vanilla')

    # Get visit count (default 0)
    visits = request.session.get('visits', 0)

    # Direct access (may raise error)
    cart = request.session['cart']

Pro tip: Always use .get() with a default to avoid errors!

Deleting from Sessions (DELETE)

Remove specific data or clear everything:

def logout_user(request):
    # Remove one item
    del request.session['favorite']

    # Remove if it exists (safer)
    request.session.pop('cart', None)

    # Clear EVERYTHING
    request.session.flush()

Checking Session Data (EXISTS)

See if something is stored:

def check_login(request):
    # Check if key exists
    if 'user_id' in request.session:
        return "You're logged in!"
    else:
        return "Please log in"

    # Get all keys
    all_keys = request.session.keys()

Complete Example: Visit Counter

def welcome(request):
    # Get current count (default 0)
    visits = request.session.get('visits', 0)

    # Add one more visit
    visits += 1

    # Save back to session
    request.session['visits'] = visits

    # Show message
    if visits == 1:
        msg = "Welcome, first-timer!"
    else:
        msg = f"Welcome back! Visit #{visits}"

    return HttpResponse(msg)

🍪 Cookies

What is a Cookie?

A cookie is a tiny piece of text your browser stores. It’s like a sticky note your browser keeps for each website.

Important difference:

  • Sessions = Data stored on SERVER (private)
  • Cookies = Data stored in BROWSER (visible to user)

Cookie vs Session: Quick Comparison

graph TD subgraph Cookie A["Stored in browser"] B["User can see it"] C["Limited size ~4KB"] D["Can be modified by user"] end subgraph Session E["Stored on server"] F[User can't see it] G["Unlimited size"] H["Secure from tampering"] end

Setting Cookies in Django

def set_cookie(request):
    response = HttpResponse("Cookie set!")

    # Basic cookie
    response.set_cookie('theme', 'dark')

    # Cookie with expiry (30 days)
    response.set_cookie(
        'remember_me',
        'yes',
        max_age=30*24*60*60  # 30 days in seconds
    )

    # Secure cookie (HTTPS only)
    response.set_cookie(
        'secure_data',
        'secret123',
        secure=True,
        httponly=True
    )

    return response

Reading Cookies

def read_cookie(request):
    # Get cookie with default
    theme = request.COOKIES.get('theme', 'light')

    # Check if cookie exists
    if 'remember_me' in request.COOKIES:
        auto_login = True

    return HttpResponse(f"Theme: {theme}")

Deleting Cookies

def delete_cookie(request):
    response = HttpResponse("Cookie deleted!")

    # Delete by setting empty value
    response.delete_cookie('theme')

    return response

Cookie Settings Explained

Parameter What It Does Example
max_age Seconds until expiry 3600 (1 hour)
expires Exact expiry date datetime object
secure HTTPS only True
httponly No JavaScript access True
samesite Cross-site rules 'Strict' or 'Lax'

When to Use What?

Use Session For Use Cookie For
User login info Theme preference
Shopping cart Language choice
Sensitive data “Remember me” flag
Large data Small preferences

🎓 Putting It All Together

Real-World Example: Remember User Theme

def set_theme(request, theme_name):
    # Store in COOKIE (survives logout)
    response = redirect('home')
    response.set_cookie(
        'theme',
        theme_name,
        max_age=365*24*60*60  # 1 year
    )
    return response

def home(request):
    # Read from cookie
    theme = request.COOKIES.get('theme', 'light')
    return render(request, 'home.html', {
        'theme': theme
    })

Real-World Example: Shopping Cart

def add_to_cart(request, item_id):
    # Get cart from SESSION (secure)
    cart = request.session.get('cart', [])

    # Add item
    cart.append(item_id)

    # Save back
    request.session['cart'] = cart

    return redirect('cart')

def view_cart(request):
    cart = request.session.get('cart', [])
    return render(request, 'cart.html', {
        'cart': cart
    })

🚀 Key Takeaways

  1. Sessions = Server-side memory (secure, hidden)
  2. Cookies = Browser-side storage (visible, limited)
  3. Session ID = The link between cookie and session data
  4. Use sessions for sensitive data (login, cart)
  5. Use cookies for preferences (theme, language)
  6. Always set httponly=True and secure=True for safety!

🎉 You Did It!

You now understand how Django remembers its visitors! Think of it this way:

Cookies are like name tags visitors wear. Sessions are like the shop’s private customer files. Together, they make your website feel personal and smart!

Now go build something amazing! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.