Quick Contact

    Python Tutorial
    Python Panda Tutorial
    Python Selenium
    Python Flask Tutorial
    Python Django
    Interview Questions & Answers

    Django Cookies and Cookies Handling

    When we see the word cookies, we expect a chocolate chip baked biscuit, but here we will talk about computer cookies. They do a great piece of work that makes it more easy for you to surf the Internet but they can be irritating if you do not know how to remove or delete cookies.

    What are Cookies?

    Cookies, technically called HTTP Cookies are small text files which are created and maintained by your browser on the particular request of Web-Server. They are stored locally by your browser, and most browser will also show you the cookies generated in the Privacy and Security settings of the browser.

    HTTP is a stateless protocol. When any request is sent to the server, over this protocol, the server cannot distinguish whether the user is new or has visited the site previously.

    Suppose, you are logging in any website, that website will respond the browser with some cookies which will have some unique identification of user generated by the server and some more details according to the context of the website.

    Cookies made these implementations possible with ease which were previously not possible over HTTP implementation.

    How do Cookies work?

    Cookies work like other HTTP requests over the Internet. In a typical web-system, the browser makes a request to the server. The server then sends the response along with some cookies, which may contain some login information or some other data.

    When the browser makes a new request, the cookie generated previously is also transmitted to the server. This process is repeated every time a new request is made by the browser.

    The browser repeats the process until the cookie expires or the session is closed and the cookie is deleted by the browser itself.

    Then, the cookie applies in all sorts of tasks, like when your login to a website or when shopping online on the web. Google AdSense and Google Analytics can also track you using the cookies they generate. Different websites use cookies differently according to their needs.

    Now, let’s move on to the core section in which you will learn to create cookies in the Django framework.

    Creating Cookies in Django

    Django bypasses lots of work which otherwise would be required when working on cookies.

    Django has methods like set_cookie() which we can use to create cookies very easily.

    The set_cookie() has these attributes:


    It specifies the name of cookie.


    It specifies the text or variable you want to store in the cookie.


    It is the time period of cookie in seconds. After the time period completes, it will expire. It is an optional parameter; if not present then the cookie will exist till the time browser close.


    html = HttpResponse("< h1>DucatindiaDjango Tutorial< /h1>")
    html.set_cookie('ducatindia', 'Hello this is your Cookies', max_age = None)
    return html

    This function will return to the browser, and when you run it, you can check the created cookie in your browser settings.

    Read Cookies from request

    Cookies pass to the particular website every time the client makes a request. Therefore, server every time receives a cookie alongside the request. Django makes it very easy for us to retrieve data from a cookie.

    1. Using request.COOKIES[]

      Django’s request object has an attribute COOKIES, like COOKIES array in PHP.

      COOKIES is a special attribute of request, and its value is the name of the cookie from which you want to read data. Since there can be multiple cookies, you can change this value many times according to the type of cookie you want to store.

      Here is how you can use the same.

      We will use basic syntax to access a class parameter as:




      show = request.COOKIES[‘ducatindia’]

      html = “< center> New Page < br>{0}< /center>“.format(show)


    2. Using request.COOKIES.get()

      Django also provides a method to get the desired value from the cookie. You can directly access that value using get method over request object.

      The syntax that we will request :

      COOKIES.get(‘cookie_name’, ‘value’)

      Let’s make some changes in our previous example.

      In our views.py write this code

      fromdjango.shortcuts import render, redirect

      fromdjango.http import HttpResponse

      We will need to apply redirect(), so import it.

    3. Code:

      html = HttpResponse("< h1>ducatindiaDjango Tutorial< /h1>")
      html.set_cookie('ducatindia', 'Welcome Back')
      value = int(request.COOKIES.get('visits'))
      html.set_cookie('visits', value + 1)
      value = 1
      text = "Welcome for the first time"
      html.set_cookie('visits', value)
      html.set_cookie('dataflair', text)
      return html

      This code will check whether the request has cookies or not, it will then set the cookies according to that.

      We will use the COOKIES.get() to achieve that.

      Now, make the change to our showcookie()


      ifrequest.COOKIES.get('visits') is not None:
      value = request.COOKIES.get('visits')
      text = request.COOKIES.get('dataflair')
      html = HttpResponse("< center>< h1>{0}< br>You have requested this page {1} times< /h1>< /center>".format(text, value))
      html.set_cookie('visits', int(value) + 1)
      return html
      return redirect('/setcookie')

      You should see an output like this. Then, the code checks whether the cookie has a value or not and if it doesn’t find anything it will redirect you to the setcookie.

    Deleting a Cookie in Django

    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()

    The delete_cookie() takes in the name of the cookie to be deleted, and this method is associated with the response object.

    Add this function to your views.py file


    response = HttpResponse("< h1>ducatindia< br>Cookie deleted< /h1>")
    response = HttpResponse("< h1>ducatindia< /h1>need to create cookie before deleting")
    return response





    Apply now for Advanced Python Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.