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