how to access cookies in django
- To access cookies in Django, import the necessary module by adding the following line to your views or middleware:
from django.http import HttpResponse
- In your view function or middleware, use the
request.COOKIES
attribute to access the cookies. For example:
def my_view(request):
cookie_value = request.COOKIES.get('cookie_name', 'default_value')
# Your code here
return HttpResponse("Cookie Value: {}".format(cookie_value))
Replace 'cookie_name'
with the name of the cookie you want to access and 'default_value'
with the default value to be used if the cookie is not present.
- To set cookies, use the
HttpResponse
class and itsset_cookie
method. For example:
def set_cookie_view(request):
response = HttpResponse("Cookie set successfully!")
response.set_cookie('cookie_name', 'cookie_value', max_age=3600)
# Your code here
return response
Replace 'cookie_name'
with the desired cookie name, 'cookie_value'
with the value to be set, and max_age
with the cookie's expiration time in seconds.
Note: Make sure to replace the placeholder names and values with your actual cookie names and values.