{"id":5578,"date":"2022-11-16T03:18:32","date_gmt":"2022-11-16T03:18:32","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=5578"},"modified":"2022-12-03T04:33:29","modified_gmt":"2022-12-03T04:33:29","slug":"django-cookies","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/django-tutorial\/django-cookies\/","title":{"rendered":"Django Cookies"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about cookies and how to set and get cookies in Django web applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-http-cookies'>Introduction to HTTP cookies <a href=\"#introduction-to-http-cookies\" class=\"anchor\" id=\"introduction-to-http-cookies\" title=\"Anchor for Introduction to HTTP cookies\">#<\/a><\/h2>\n\n\n\n<p>When a web server interacts with many different browsers at the same time, it needs to identify which browser a specific request came from.<\/p>\n\n\n\n<p>Because the HTTP request\/response is stateless, all web browsers look identical. To identify the web browsers, the web server uses cookies.<\/p>\n\n\n\n<p>Technically, cookies are text files with a small piece of data that the web server sends to a web browser.   The web browser may store the cookie and send it back to the web server in subsequent requests.  <\/p>\n\n\n\n<p class=\"note\">Note that the web browser only sends back cookies that were originally set by the same web server.<\/p>\n\n\n\n<p>By comparing the cookies, the web server can identify that the requests come from the same web browser. <\/p>\n\n\n\n<p>Cookies have expiration dates. Some may last for years while others are short-term and expired as soon as you close the web browsers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='django-cookies'>Django Cookies <a href=\"#django-cookies\" class=\"anchor\" id=\"django-cookies\" title=\"Anchor for Django Cookies\">#<\/a><\/h2>\n\n\n\n<p>Django allows you to set, read, and delete cookies via methods of the <code>HttpResponse<\/code> object.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='setting-a-cookie'>Setting a cookie <a href=\"#setting-a-cookie\" class=\"anchor\" id=\"setting-a-cookie\" title=\"Anchor for Setting a cookie\">#<\/a><\/h3>\n\n\n\n<p>To set a cookie, you use the <code>set_cookie()<\/code> method of the <code>HttpResponse<\/code> object:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">set_cookie(key, value=<span class=\"hljs-string\">''<\/span>, max_age=<span class=\"hljs-literal\">None<\/span>, expires=<span class=\"hljs-literal\">None<\/span>, path=<span class=\"hljs-string\">'\/'<\/span>, domain=<span class=\"hljs-literal\">None<\/span>, secure=<span class=\"hljs-literal\">False<\/span>, httponly=<span class=\"hljs-literal\">False<\/span>, samesite=<span class=\"hljs-literal\">None<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this method:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>key<\/code> is the cookie name.<\/li>\n\n\n\n<li><code>value<\/code> is a string that represents the cookie&#8217;s value.<\/li>\n\n\n\n<li><code>max_age<\/code> can be a timedelta object or an integer that denotes the number of seconds that specifies how long the cookie should expire. It defaults to None that expires cookie once you close the browser.<\/li>\n\n\n\n<li><code>expires<\/code> should be either a datetime object in UTC or a string in the format <code>\"Wdy,&nbsp;DD-Mon-YY&nbsp;HH:MM:SS&nbsp;GMT\"<\/code>.<\/li>\n\n\n\n<li>Use&nbsp;<code>secure=True<\/code>&nbsp;when you want the web browser to send the cookie to the server if the request is HTTPS only.<\/li>\n\n\n\n<li>Use&nbsp;<code>httponly=True<\/code>&nbsp;if you don&#8217;t want the client-side JavaScript to access the cookie.<\/li>\n\n\n\n<li>Use&nbsp;<code>samesite='None'<\/code>&nbsp;(string) to allow the cookie to be sent with all same-site and cross-site requests.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id='deleting-a-cookie'>Deleting a cookie <a href=\"#deleting-a-cookie\" class=\"anchor\" id=\"deleting-a-cookie\" title=\"Anchor for Deleting a cookie\">#<\/a><\/h3>\n\n\n\n<p>To delete a cookie, you use the <code>delete_cookie()<\/code> method of the <code>HttpResponse<\/code> object:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">delete_cookie(key, path=<span class=\"hljs-string\">'\/'<\/span>, domain=<span class=\"hljs-literal\">None<\/span>, samesite=<span class=\"hljs-literal\">None<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>delete_cookie()<\/code> method deletes a cookie with a specified name. It fails silently if the key doesn&#8217;t exist.<\/p>\n\n\n\n<p>Note that the path and domain must have the same values as you used in the <code>set_cookie()<\/code> method or the cookie will not be deleted.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='reading-cookies'>Reading cookies <a href=\"#reading-cookies\" class=\"anchor\" id=\"reading-cookies\" title=\"Anchor for Reading cookies\">#<\/a><\/h3>\n\n\n\n<p>To access all cookies sent by the web browser, you use the <code>COOKIES<\/code> property of the <code>HttpRequest<\/code> object.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">request.COOKIES<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To access a cookie by a key, you pass the cookie name to the <code>request.COOKIES<\/code> dictionary. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">request.COOKIES&#91;<span class=\"hljs-string\">'cocoa'<\/span>]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>If the cookie <code>'cocoa'<\/code> doesn&#8217;t exist, Django will throw an error. <\/p>\n\n\n\n<p>To avoid the error, you can use the <code>get()<\/code> method of the dictionary to get a cookie if it exists or get a default value otherwise. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">request.COOKIES.get(<span class=\"hljs-string\">'cocoa'<\/span>,<span class=\"hljs-number\">1<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The code will return 1 if the cookie with the name <code>'cocao'<\/code> doesn&#8217;t exist.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='django-cookies-example'>Django cookies example <a href=\"#django-cookies-example\" class=\"anchor\" id=\"django-cookies-example\" title=\"Anchor for Django cookies example\">#<\/a><\/h2>\n\n\n\n<p>We&#8217;ll use a cookie to store whether the web browser has visited the site. When the visitor visits the site for the first time, it&#8217;ll show a message:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">Welcome to my website!<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>And from the second time, it&#8217;ll check the cookie and show the following message if the cookie with the name <code>visited<\/code> is available:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">Welcome back!<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<figure class=\"wp-block-video\"><video height=\"100\" style=\"aspect-ratio: 388 \/ 100;\" width=\"388\" controls src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/Django-cookies.mp4\"><\/video><\/figure>\n\n\n\n<p>First, define a new entry in the <code>urlpatterns<\/code> of the <code>urls.py<\/code> file of your app:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">urlpatterns = &#91;\n    path(<span class=\"hljs-string\">''<\/span>, views.home, name=<span class=\"hljs-string\">'home'<\/span>),\n]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>When you open the <code>http:\/\/127.0.0.1:8000\/<\/code>, Django will execute the <code>home() <\/code>function in the <code>views.py<\/code> file. <\/p>\n\n\n\n<p>Second, define the <code>home()<\/code> function in the <code>views.py<\/code> file:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">home<\/span><span class=\"hljs-params\">(request)<\/span>:<\/span>\n    visited = request.COOKIES.get(<span class=\"hljs-string\">'visited'<\/span>)\n    <span class=\"hljs-keyword\">if<\/span> visited:\n        response = HttpResponse(<span class=\"hljs-string\">'Welcome back!'<\/span>)\n    <span class=\"hljs-keyword\">else<\/span>:\n        response = HttpResponse(<span class=\"hljs-string\">'Welcome to my website!'<\/span>)\n        response.set_cookie(<span class=\"hljs-string\">'visited'<\/span>, <span class=\"hljs-literal\">True<\/span>)\n\n    <span class=\"hljs-keyword\">return<\/span> response<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In the <code>home()<\/code> function, we read the cookie with the name <code>visited<\/code>. If the cookie with the name visited does not exist, the homepage will display the message:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">Welcome to my website!<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Otherwise, it&#8217;ll show the message:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">Welcome back!<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Also, we set the visited cookie to True.<\/p>\n\n\n\n<p>If you view the cookie in the web browser, you&#8217;ll see the cookie with the name visited like this:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"877\" height=\"59\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-cookies-example.png\" alt=\"django cookies example\" class=\"wp-image-5610\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-cookies-example.png 877w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-cookies-example-300x20.png 300w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/11\/django-cookies-example-768x52.png 768w\" sizes=\"auto, (max-width: 877px) 100vw, 877px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A cookie is a piece of data that the web server sends to the web browser and the web browser may store it or not.<\/li>\n\n\n\n<li>The web browser sends the cookie back to the web server in the subsequent requests in the header of the HTTP request.<\/li>\n\n\n\n<li>Use the <code>set_cookie()<\/code> function of the <code>HttpResponse<\/code> object to set a cookie in Django.<\/li>\n\n\n\n<li>Use the <code>delete_cookie()<\/code> method of the <code>HttpResponse<\/code> object to delete a cookie.<\/li>\n\n\n\n<li>Use the <code>request.COOKIES<\/code> dictionary to read all cookies sent by the web browser.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"5578\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/django-tutorial\/django-cookies\/\"\n\t\t\t\tdata-post-title=\"Django Cookies\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"5578\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/django-tutorial\/django-cookies\/\"\n\t\t\t\tdata-post-title=\"Django Cookies\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about Django cookies and how to set and get cookies in Django web applications.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":5531,"menu_order":43,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-5578","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/5578","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=5578"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/5578\/revisions"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/5531"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=5578"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}