Django Cookies Handling- Cookies in Django | W3Schools

There are times when you are required to store data on a per site visitor basis which goes well with the requirement of the web application. Always remember that cookies are stored on the client side. It is also dependent on your client browser security level. Well, sometimes cookies work properly and sometimes not. This usually occurs when you make changes in the settings of the cookies.

To understand cookies handling in Django, let’s begin by creating an application which supports login system as we created earlier. The system will let you log in for a fixed period of interval. Once you exceed the time limit, the system will push you out of the application on its own.

To create such a system, you are required to set up two cookies labeled as ‘last_connection’ and ‘username’.

We will start by making a few changes in the login view where we will be making it capable of storing the values of last_connection and username cookies.

from django.template import RequestContext
def login(request):
   username = “not logged in”  
   if request.method == “POST”:
      #Get the posted form
      MyLoginForm = LoginForm(request.POST)
   if MyLoginForm.is_valid():
      username = MyLoginForm.cleaned_data[‘username’]
   else:
      MyLoginForm = LoginForm()  
   response = render_to_response(request, ‘loggedin.html’, {“username” : username},
      context_instance = RequestContext(request))  
   response.set_cookie(‘last_connection’, datetime.datetime.now())
   response.set_cookie(‘username’, datetime.datetime.now())
   return response

The above section of code helps you to understand how cookie setting is done by using set_cookie() method. This method is called on the response and not on the request. The value returned by the cookies are returned as string.

Now, for the login form, you need to create a formView. The form won’t get displayed if the cookie is not set and if the same cookie is not older than 10 seconds.

def formView(request):
   if ‘username’ in request.COOKIES and ‘last_connection’ in request.COOKIES:
      username = request.COOKIES[‘username’]     
      last_connection = request.COOKIES[‘last_connection’]
      last_connection_time = datetime.datetime.strptime(last_connection[:-7],
         “%Y-%m-%d %H:%M:%S”)     
      if (datetime.datetime.now() – last_connection_time).seconds < 10:
         return render(request, ‘loggedin.html’, {“username” : username})
      else:
         return render(request, ‘login.html’, {})                                   
   else:
      return render(request, ‘login.html’, {})

The above formView coding lets the cookie to be accessed. This has become possible by making use of COOKIES attribute which is called by the request.

After you are done with all the above mentioned steps, it’s time for you to make a few changes in the url.py file. Here, you are required to alter the required URL so that you can pair it with the newly created view.

from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns(‘myapp.views’,
   url(r’^connection/’,’formView’, name = ‘loginform’),
   url(r’^login/’, ‘login’, name = ‘login’))

Open the web browser and type in the URL: http://127.0.0.1:8000/myapp/connection/ to get to the following web page:

The entered URL will eventually redirect you to the given screen:

Once, you have the access to this page, the web page will directly appear in front of you whenever you enter the same URL within the 10 seconds’ time interval. And if you try to access the same web page after 10 seconds then you will be redirected to the login form (which is screen 1).