Photo by Vyshnavi Bisani on Unsplash
Cookies in Django
2 min read
What is Cookie?
A cookie is a small piece of data stored in the user’s browser which is sent by the server. They are commonly used to store user preferences. This is how cookies work in general:
The browser sends the request to the server.
The server sends the response along with one or more cookies to the browser.
The browser saves the cookie it received from the server. From now on, the browser will send this cookie to the server, every time a request is made to the server. The browser will keep sending the cookie to the server along with each request until the cookie expires.
When the cookie expires, it is removed from the browser.
We can create cookies using the set_cookie() method of the request object. The syntax of the method is:
set_cookie(name, value, max_age=None)
name: name of the cookie
value: value you want to store in the cookie
max_age: age of the cookie in seconds. After that, it will expire. It is an optional argument, if not given then the cookie will exist until the browser is closed.
def setcookie(request): html = HttpResponse("<h1>How to set cookie by raturi</h1>") if request.COOKIES.get('visit_count'): message = 'Thanks for visiting again' value = int(request.COOKIES.get('visit_count')) + 1 else: value = 1 message = "Welcome for the first time" html.set_cookie('visit_count', value) html.set_cookie('visitor_message', message) return html
Cookies pass to the particular website every time the client makes a request. Therefore, the server every time receives a cookie alongside the request. Django makes it very easy for us to retrieve data from a cookie.
request object in Django has a COOKIE attribute which acts like a dictionary. We can use COOKIE to access a cookie value like this:
def read_cookie(request): show = request.COOKIES['visit_count'] ...
Django provides you with easy methods for deleting cookies. As we used set_cookie() to create cookies, we can also delete cookies using a similar function, delete_cookie()
def delete_cookie(request): if request.COOKIES.get('visit_count'): response.delete_cookie("visits") ...
Did you find this article valuable?
Support Nitin Raturi by becoming a sponsor. Any amount is appreciated!