How to set and get cookies in Django
In this tutorial, we will learn how to set and get cookies in Django. Cookies are small pieces of data stored in user’s web browser by the website and they serve various purposes during browsing like personalization, authentication and session management.
Set and Get Cookies – Django
After setting up your Django project and registering your app, start thinking what all the features you need and develop a flowchart in your head. First of all, we don’t want to store any data, so we don’t need to write anything in models.py
. We want the functionality, so we need to write in views.py
, then we have to set url path so have to modify the urls.py
and finally need frontend, so web pages thus, the templates directory.
views.py
from django.shortcuts import render from django.http import HttpResponse def set_cookie(request): return render(request, 'set_cookie.html') def process_cookie(request): if request.method == 'POST': cookie_value = request.POST.get('cookie_value') response = HttpResponse("Cookie has been set.") response.set_cookie('my_cookie', cookie_value) return response else: return HttpResponse("Invalid request") def get_cookie(request): cookie_value = request.COOKIES.get('my_cookie') return render(request, 'get_cookie.html', {'cookie_value': cookie_value})
I have allowed the user to set his own cookie. So we need the input from the user and using the set_cookie
function, the cookie will be set. In the get cookie function, we will send the cookie which is set by the user and it will be displayed on web page.
app/urls.py
from django.urls import path from .views import set_cookie, process_cookie, get_cookie urlpatterns = [ path('set_cookie/', set_cookie, name='set_cookie'), path('process_cookie/', process_cookie, name='process_cookie'), path('get_cookie/', get_cookie, name='get_cookie'), ]
Templates
We need two web pages, one for setting the cookies and one for displaying it.
set_cookie.html
<!DOCTYPE html> <html> <head> <title>Set Cookie</title> </head> <body> <h1>Set Cookie</h1> <form method="post" action="{% url 'process_cookie' %}"> {% csrf_token %} <label for="cookie_value">Enter Cookie Value:</label> <input type="text" id="cookie_value" name="cookie_value"> <button type="submit">Set Cookie</button> </form> </body> </html>
After clicking on Set Cookie button, you will see the dialogue that the cookie has been set.
get_cookie.html
<!DOCTYPE html> <html> <head> <title>Get Cookie</title> </head> <body> <h1>Get Cookie</h1> {% if cookie_value %} <p>The value of the cookie is: {{ cookie_value }}</p> {% else %} <p>No cookie has been set.</p> {% endif %} </body> </html>
In this webpage, you can see the cookie which is set up by the user.
Now you know how to set and get cookie, you can use it in your project to give better functionality.
Leave a Reply