{"id":8197,"date":"2020-08-29T19:53:02","date_gmt":"2020-08-29T19:53:02","guid":{"rendered":"https:\/\/www.askpython.com\/?p=8197"},"modified":"2023-05-10T14:27:02","modified_gmt":"2023-05-10T14:27:02","slug":"django-cookies","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/django\/django-cookies","title":{"rendered":"Django Set Cookies &#8211; Setting up User Cookies in Django"},"content":{"rendered":"\n<p>Cookies play an important role in web applications. They allow websites to save small pieces of data on the user&#8217;s computer that can be accessed again when the user revisits the site. In Django, it&#8217;s simple to set up and work with cookies.&nbsp;<\/p>\n\n\n\n<p>In this article, we&#8217;ll explore how to set, retrieve, and delete cookies in Django. Cookies allow us to build a smooth user experience by remembering users and their preferences. By the end, you&#8217;ll be able to use cookies in your own Django projects!&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to Cookies<\/h2>\n\n\n\n<p>Cookies are small pieces of data stored on a user&#8217;s computer by the web browser. They are used by websites to store information about the user and their preferences to enhance the user experience.<\/p>\n\n\n\n<p>When a user visits a website, the website can set one or more cookies on the user&#8217;s computer. When the same user visits the website again, the website can read the cookies to remember the user and their preferences. This leads to a smoother browsing experience as the website can be customized for the user without asking them to enter the same information again.<\/p>\n\n\n\n<p><strong>Cookies are stored as name-value pairs, e.g. username=John. <\/strong><\/p>\n\n\n\n<p>They contain a name, value, domain, path, expiration date, and security settings. The domain specifies which websites can access the cookie. The path indicates a URL subset within the domain where the cookie is used.&nbsp;<\/p>\n\n\n\n<p><strong><em>Also read: <a href=\"https:\/\/www.askpython.com\/python\/dictionary\/python-dictionary-dict-tutorial\" data-type=\"post\" data-id=\"535\">Python Dictionary (Dict) Tutorial<\/a><\/em><\/strong><\/p>\n\n\n\n<p>The expiration date determines when the browser should delete the cookie. Security settings control if the cookie should only be transmitted over HTTPS.<\/p>\n\n\n\n<p>There are two main types of cookies: session cookies and persistent cookies. Session cookies are deleted when the user closes the browser, whereas persistent cookies are saved for a long period of time based on the expiration date. Persistent cookies should require user consent according to privacy laws.<\/p>\n\n\n\n<p>Cookies provide many useful features for enhancing web applications and customizing the user experience. However, they also raise some privacy concerns as websites can access personal information stored in cookies. Most browsers allow users to view, modify, and delete cookies to give them more control over their privacy.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding the Role of Cookies<\/h2>\n\n\n\n<p>Http is a stateless protocol which means that a web server cannot distinguish whether you are visiting the page for the first time or whether you have visited previously as well.<\/p>\n\n\n\n<p>So when you visit a page for the first time, the server responds to the browser with cookies which contains information like the user information generated by the server, etc.<\/p>\n\n\n\n<p>That cookie is stored in your browser. So when you visit again, the cookie-generated earlier is also sent to the server along with the HTTP request. The server can then read the cookie and perform appropriate tasks.<\/p>\n\n\n\n<p>The browser keeps sending the cookies until they get expired and after that are automatically discarded from the browser.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why are cookies used?<\/h3>\n\n\n\n<p>In any eCommerce or social media site like Facebook, you might have observed that if you leave the site without logging out, the next time you go to the site, your account continues to stay logged in. This is done using cookies (which contain user session information).<\/p>\n\n\n\n<p>Similarly, in many eCommerce websites, you get recommendations about different products. Again this because of the cookies storing the search information in your browser<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Working with Django Set Cookie: Setting and Retrieving Cookies<\/h2>\n\n\n\n<p>We will now see a simple application of cookies and learn how to use them. Python Django provides a built-in method to use cookies.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Django Set Cookie Attributes<\/h3>\n\n\n\n<p>A Django cookie attribute can perform one of two actions. It can drop a cookie in a user&#8217;s computer (set) and then access those cookies(get). Let&#8217;s look at both the methods here.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Set cookies<\/h4>\n\n\n\n<p>This cookie attribute creates a cookie, which is then sent <strong>by the server<\/strong> <strong>to the user browser<\/strong> to store information. The syntax for set_cookie() is:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nset_cookie(cookie_name, value, max_age = None, expires = None) \n<\/pre><\/div>\n\n\n<h4 class=\"wp-block-heading\">Get cookies<\/h4>\n\n\n\n<p>This attribute is used by the server to get back the previously sent cookies and read data from it. The syntax to get the cookie is:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nrequest.COOKIES&#x5B;&#039;cookie_Name&#039;]\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Implementing Cookie Handling in Django Views<\/h3>\n\n\n\n<p>Now that we know the methods that Django cookies can work with let&#8217;s set up our views to set those cookies and then access those back. We&#8217;ll build up from our Django views article to set up the cookies.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">View for sending Cookie<\/h4>\n\n\n\n<p>Add the following view into your views.py file<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef SetCookie(request):\n    response = HttpResponse(&#039;Visiting for the first time&#039;)\n    response.set_cookie(&#039;bookname&#039;,&#039;Sherlock Holmes&#039;)\n    return response\n<\/pre><\/div>\n\n\n<p>The URL path will be:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\npath(&#039;setcookie\/&#039;, SetCookie),\n<\/pre><\/div>\n\n\n<h4 class=\"wp-block-heading\">View for getting back the Cookie<\/h4>\n\n\n\n<p>Add the following view into your views.py<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef GetCookie(request):\n    bookname = request.COOKIES&#x5B;&#039;bookname&#039;]\n    return HttpResponse(f&#039;The book name is: {bookname}&#039;)\n<\/pre><\/div>\n\n\n<p>The URL path will be:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\npath(&#039;getcookie\/&#039;, GetCookie),\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Putting It All Together: A Complete Django Set Cookie Example<\/h2>\n\n\n\n<p>Now that we\u2019ve discussed the individual Views required, Here is the combined script (including both the above section codes) for the Views.py. <\/p>\n\n\n\n<p>Simply add the below code in your <strong>views.py <\/strong>along with the URL maps and we are good to go:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom django.shortcuts import HttpResponse\n\ndef SetCookie(request):\n    response = HttpResponse(&#039;Visiting for the first time&#039;)\n    response.set_cookie(&#039;bookname&#039;,&#039;Sherlock Holmes&#039;)\n    return response\n\ndef GetCookie(request):\n    bookname = request.COOKIES&#x5B;&#039;bookname&#039;]\n    return HttpResponse(f&#039;The book name is: {bookname}&#039;)\n<\/pre><\/div>\n\n\n<p>The urls.py file will look like:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom django.contrib import admin\nfrom django.urls import path\nfrom .views import SetCookie, GetCookie\n\nurlpatterns = &#x5B;\n    path(&#039;setcookie\/&#039;, SendCookie),\n    path(&#039;getcookie\/&#039;, GetCookie),\n]\n<\/pre><\/div>\n\n\n<p>That\u2019s it, guys !! Let us now run the server and check !!<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"682\" height=\"205\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/08\/image-30.png\" alt=\"Set Cookie\" class=\"wp-image-8198\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/08\/image-30.png 682w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/08\/image-30-300x90.png 300w\" sizes=\"auto, (max-width: 682px) 100vw, 682px\" \/><figcaption class=\"wp-element-caption\">Set Cookie<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"682\" height=\"205\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/08\/image-31.png\" alt=\"Get Cookie\" class=\"wp-image-8199\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/08\/image-31.png 682w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/08\/image-31-300x90.png 300w\" sizes=\"auto, (max-width: 682px) 100vw, 682px\" \/><figcaption class=\"wp-element-caption\">Get Cookie<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Master Django Set Cookie for Better User Experience<\/strong><\/h2>\n\n\n\n<p>Cookies are powerful tools in any web developer&#8217;s toolkit. They allow us to build intelligent, personalized user experiences that feel like magic. In this article, we&#8217;ve explored the wonderful world of cookies in Django.<\/p>\n\n\n\n<p>With just a few lines of Python and Django, you can set cookies to remember your users, store their preferences, keep them logged in, and track their activity. Cookies are what power many of the internet&#8217;s coolest features!<\/p>\n\n\n\n<p>We&#8217;ve seen how to bake cookies (with set_cookie()), access cookies in views, choose between sesion or permanent cookies, and delete cookies when they&#8217;re no longer needed. Django makes working with cookies a piece of cake.<\/p>\n\n\n\n<p>Now that you&#8217;ve got the recipe for Django cookies, what will you create? A personalized dashboard for your users? A login system? Shopping cart? Product recommendations? The possibilities are endless.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Cookies play an important role in web applications. They allow websites to save small pieces of data on the user&#8217;s computer that can be accessed again when the user revisits the site. In Django, it&#8217;s simple to set up and work with cookies.&nbsp; In this article, we&#8217;ll explore how to set, retrieve, and delete cookies [&hellip;]<\/p>\n","protected":false},"author":13,"featured_media":8235,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[111],"tags":[],"class_list":["post-8197","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-django"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/8197","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=8197"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/8197\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/8235"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=8197"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=8197"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=8197"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}