Django Cookies

Django cookies are small pieces of data stored on a user’s browser, sent by the server, and used to persist information about a user across multiple requests. Cookies are useful for tasks like tracking user sessions, storing preferences, and maintaining temporary data.

How Cookies Work in Django?

1. Setting Cookies: The server sends cookies to the client’s browser via the response.

2. Storing Cookies: The browser stores the cookies and includes them in subsequent requests to the same server.

3. Accessing Cookies: The server reads cookies from the incoming request for specific data.

How to use Cookies in Django?

1. Setting Cookies

You can set a cookie in the response using the set_cookie method:


from django.http import HttpResponse

def set_cookie(request):
    response = HttpResponse("Cookie has been set!")
    response.set_cookie('user_name', 'John', max_age=3600)  # Cookie valid for 1 hour
    return response

Parameters Details:

Key: The name of the cookie (‘user_name’).

Value: The data stored in the cookie (‘John’).

max_age: Expiry time in seconds (optional).

expires: Date and time when the cookie expires (optional).

secure: If True, the cookie is sent only over HTTPS.

httponly: If True, the cookie is inaccessible to JavaScript (adds security).

2. Accessing Cookies

You can access cookies from the request object using request.COOKIES:


def get_cookie(request):
    user_name = request.COOKIES.get('user_name', 'Guest')  # Default to 'Guest' if cookie not set
    return HttpResponse(f"Hello, {user_name}!")

3. Deleting Cookies

To delete a cookie, use the delete_cookie method:


def delete_cookie(request):
    response = HttpResponse("Cookie has been deleted!")
    response.delete_cookie('user_name')
    return response

Django Cookies – Interview Questions

Q 1: What are cookies in Django?
Ans: Small data stored on the client browser.
Q 2: How do you set a cookie in Django?
Ans: Using response.set_cookie().
Q 3: How do you read cookies?
Ans: Using request.COOKIES.
Q 4: Difference between cookies and sessions?
Ans: Cookies store data on client, sessions on server.
Q 5: Are cookies secure?
Ans: They should be encrypted and used carefully.

Django Cookies – Objective Questions (MCQs)

Q1. Cookies store data on the:






Q2. Which Django method sets a cookie?






Q3. Which method retrieves a cookie?






Q4. Cookies are mostly used for:






Q5. To delete a cookie, Django uses:






Related Django Cookies Topics