Django Sessions | Create a Session in Django- W3Schools

As we have already mentioned earlier that the client side cookies are usually used to store numerous meaningful data for the web application. This gives rise to an issue of security of data that has been stored in the client side cookies.

To overcome this security issue, Django offers a session framework which especially deals with the cookies handling. This session framework of Django abstracts the receiving and sending of cookies. It also saves all the data on the server side (as done in a database) and on the client side, the cookie just carries the session ID for the identification purpose. This framework also steps in whenever the user browser is set to not accept cookies.

How to Set Up Sessions?

In Django, you need to start by enabling the session which will be under the settings.py file. Under this file, add a few lines of code to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This setting needs to be done while you are creating the project. The MIDDLEWARE_CLASSES should carry the following code –
‘django.contrib.sessions.middleware.SessionMiddleware’

Ensure that INSTALLED_APPS should have –
‘django.contrib.sessions’

In general, Django stores all the information regarding the sessions in a database named as django_session (you can either call it a table or a collection). But, Django framework offers you an option of storing your sessions either in a file or in a cache memory, as per your requirement.

Whenever the session gets enabled, every request (any of the view of the Django which receives the first argument or parameter) has a session (dict) attribute of its own.

In here, we will help you in creating and storing sessions. In earlier chapters like in Django Form Processing chapter and in Django Cookies Handling chapter, we have created a login form. So, we will start by saving the username in a cookie. In this way, if the user has decided not to sign out then he/she will land up on the login web page and won’t be able to see the login form. In short, we are creating a system which is more secure than the system which we have created in Django Cookies Handling chapter. This system is more secure than the previous one as here, we will be saving our cookies on the server side (in the previous case, it was stored on the client side browser).

For this to take place, you are required to change the already created login view to save the username in the server side cookie.

def login(request):
   username = ‘not logged in’
      if request.method == ‘POST’:
      MyLoginForm = LoginForm(request.POST)      
      if MyLoginForm.is_valid():
         username = MyLoginForm.cleaned_data[‘username’]
         request.session[‘username’] = username
      else:
         MyLoginForm = LoginForm()
   return render(request, ‘loggedin.html’, {“username” : username}

After this, there’s a need to create a view (here, we are creating it under the name of formView) for the login form. Remember that in this view if the cookie is set then the form won’t get displayed to the user.

def formView(request):
   if request.session.has_key(‘username’):
      username = request.session[‘username’]
      return render(request, ‘loggedin.html’, {“username” : username})
   else:
      return render(request, ‘login.html’, {})

The last step is to make a few alterations in the url.py file. In this file, you need to pair the URL to 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’))

Now, to access this view on the web browser, type in the given URL: http://127.0.0.1:8000/myapp/connection/ and you will land up on the below shown screen.

Finally, you will be redirected to the following web page –

According to our coding, whenever the user tries to access the same URL (http://127.0.0.1:8000/myapp/connection/) again, he/she will be directly reach to the second screen.

To erase the cookie, we are now creating a basic logout view.

def logout(request):
   try:
      del request.session[‘username’]
   except:
      pass
   return HttpResponse(“<strong>You are logged out.</strong>”)

To pair this logout view to a logout URL, add the following code to the myapp/url.py file –

url(r’^logout/’, ‘logout’, name = ‘logout’),

When you access the URL: http://127.0.0.1:8000/myapp/logout/, the following web page will appear –

To verify whether the logout view worked properly or not, you just need to re-access the URL: http://127.0.0.1:8000/myapp/connection/. It will display the login form (which is screen 1).

Other Possible Actions By Using Sessions

After knowing how to save and access a session, it would be helpful for you to know other possible actions that can be performed by using session attribute.

* set_expiry (value) – This method sets an expiry for the session.

* get_expiry_age() – This method returns the seconds until which the session expired.

* get_expiry_date() – This method returns the date in which the session will expire.

* clear_expired() – This method is used to clear all the expired sessions from the database of the Django sessions.

* get_expire_at_browser_close() – This method returns a bool value (which could be true or false). This completely depends upon the expiry of the user’s session cookies at the time when the user’s web browser is closed.