Python > Web Development with Python > Django > Sessions and Cookies
Django Cookie Example: Setting and Retrieving Cookies
This snippet shows how to set and retrieve cookies in a Django view. Cookies are small text files that websites store on a user's computer to remember information about them. This can be used for a variety of purposes, such as storing user preferences, tracking website usage, or managing shopping carts.
Setting up the Django View
This code defines two Django views: set_cookie
and get_cookie
.set_cookie
: This view creates an HttpResponse
object and uses the set_cookie
method to set a cookie named user_id
with the value '12345'
. The max_age
parameter specifies how long the cookie should be stored in seconds (in this case, 1 hour). The response is then returned to the client, which stores the cookie in the user's browser.get_cookie
: This view retrieves the value of the user_id
cookie using request.COOKIES.get('user_id', 'Not set')
. The second argument to get
is a default value that will be returned if the cookie is not found. The view then renders a template (get_cookie.html
) displaying the retrieved cookie value.
from django.shortcuts import render, HttpResponse
def set_cookie(request):
response = HttpResponse('Cookie set!')
response.set_cookie('user_id', '12345', max_age=3600) # Expires in 1 hour
return response
def get_cookie(request):
user_id = request.COOKIES.get('user_id', 'Not set') # 'Not set' is the default value
return render(request, 'get_cookie.html', {'user_id': user_id})
Defining the URLs
This code defines the URL patterns for the views. The set_cookie/
URL maps to the set_cookie
view, and the get_cookie/
URL maps to the get_cookie
view. The name
argument allows you to easily reference these URLs in your templates.
from django.urls import path
from . import views
urlpatterns = [
path('set_cookie/', views.set_cookie, name='set_cookie'),
path('get_cookie/', views.get_cookie, name='get_cookie'),
]
Template Example (get_cookie.html)
This is a simple example template to display the cookie value and provide a link to the other view.get_cookie.html
: Displays the user_id
value retrieved from the cookie and provides a link to the set_cookie
view.
<!-- get_cookie.html -->
<h1>User ID: {{ user_id }}</h1>
<a href="{% url 'set_cookie' %}">Set Cookie</a>
Concepts Behind the Snippet
This snippet illustrates the fundamental concepts of using cookies in Django:
request.COOKIES
: This object provides a dictionary-like interface for accessing cookies sent by the client.
Real-Life Use Case
A common use case for cookies is remembering user preferences, such as their preferred language or theme. For example, you could set a cookie to store the user's language preference, and then use that preference to display the website in the appropriate language on subsequent visits.
Best Practices
Here are some best practices for working with cookies in Django:
SESSION_COOKIE_SECURE
setting can also be applied to cookies you set manually if you implement your own session-like system. Also set the HttpOnly
flag to prevent client-side scripts from accessing the cookie.max_age
parameter or the expires
parameter (for a specific date/time) when setting a cookie.
Interview Tip
When discussing cookies in an interview, be prepared to explain how they work, their purpose, security considerations, and size limitations. Also, be able to describe the difference between cookies and sessions, and when to use each.
When to Use Cookies
Use cookies when you need to store small amounts of non-sensitive data on the client's computer. This is common for:
Memory Footprint
Cookies have minimal memory footprint on the server-side since they are stored on the client-side. However, excessive use of large cookies can slow down website loading times due to the overhead of sending cookies with each request.
Alternatives
Alternatives to cookies for storing user data include:
Pros
The pros of using cookies in Django:
Cons
The cons of using cookies in Django:
FAQ
-
How do I delete a cookie?
You can delete a cookie by setting its
max_age
to 0 or by callingresponse.delete_cookie('cookie_name')
. -
What is the difference between
max_age
andexpires
?
max_age
specifies the cookie's lifetime in seconds, whileexpires
specifies the exact date and time when the cookie should expire.max_age
is generally preferred. -
How can I make a cookie secure?
Set the
secure
flag toTrue
when setting the cookie. This will ensure that the cookie is only sent over HTTPS connections. Also, set theHttpOnly
flag toTrue
to prevent client-side scripts from accessing the cookie.