Home >>Django Tutorial >Django Cookie
A cookie is a small piece of information that is stored in the client's browser. It is used to store the user's data in a file for the specified time.
Cookie has some expiry date and time and it gets removed automatically when it expires. Django provides some built-in methods to set and fetch the cookie.
The set_cookie() method is used to set a cookie and the get() method is used to get the cookie.
The request.COOKIES['key'] array is also used to get the cookie values.
from django.shortcuts import render
from django.http import HttpResponse
def setcookie(request):
response = HttpResponse("Cookie Set")
response.set_cookie('java-tutorial', 'javatpoint.com')
return response
def getcookie(request):
tutorial = request.COOKIES['java-tutorial']
return HttpResponse("java tutorials @: "+ tutorial);
Now we will specify the URLs to access these functions:
// urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('scookie',views.setcookie),
path('gcookie',views.getcookie)
]
Start Server
$ python3 manage.py runserver
After starting the server, we will set the cookie by using localhost:8000/scookie URL.
And we can get a cookie by using localhost:8000/gcookie URL. It will show the set cookie to the browser.