In Django, cookies are used to store small amounts of data on the client side. They can contain key-value pairs of user information that the website uses to remember user preferences, sessions, and other data to provide a better user interface (UI).
To use cookies in Django, the ‘HttpResponse’ and ‘HttpRequest’ objects are used. The ‘HttpResponse’ object has a set\_cookie method that lets you set a cookie. The cookie’s value can be retrieved from a ‘HttpRequest’ object using the COOKIES attribute.
Below is an example of how to set a cookie in Django:
```
def set_cookie(request):
response = HttpResponse(“Setting a cookie”)
response.set_cookie(‘django_cookie’, ‘django_cookie_value’)
return response
```
In this example, `django_cookie` is the name of the cookie and `django_cookie_value` is the value of the cookie. This cookie will be sent in the response and is stored on the client’s side.
Here is an example of how to get a cookie’s value in Django:
```
def get_cookie(request):
django_cookie_value = request.COOKIES[‘django_cookie’]
return HttpResponse(“The value of ‘django_cookie’ is “+ django_cookie_value)
```
In this example, we have used the HttpRequest object’s “COOKIES” attribute to fetch the data of the cookie. Keep in mind that cookies are stored as strings, so you need to convert this value into a different data type if required.
You can also set some optional parameters for a cookie such as max\_age (to set lifetime in seconds for the cookie), expires (to set Expiry date for the cookie in datetime object or timedelta), domain (to set domain that can read the cookie) and secure (to instruct the browser to only send the cookie over HTTPS).
```
def set_cookie(request):
response = HttpResponse(“Setting a cookie”)
response.set_cookie(‘django_cookie’, ‘django_cookie_value’, max_age=60*60*24*365*2, domain=‘www.django.com’, secure=True)
return response
```
Django provides an extra level of security for cookie handling. Your settings.py file includes SESSION_COOKIE_SECURE = False by default. If you set this setting to True, Django won’t allow the cookie to be sent over HTTP – only HTTPS. This does not guarantee that the cookie is secure, but it is a step in the right direction to prevent it from being sent in plain text, where it could potentially be intercepted and stolen.
These examples and information are derived from Django’s official documentation.
Source:
- Django Official Documentation: How to use sessions. (n.d.). Retrieved from https://docs.djangoproject.com/en/4.0/topics/http/sessions/