Table of contents
1.
Introduction
2.
Setting Up Sessions
3.
Some More Possible Actions Using Sessions
4.
Frequently asked questions
5.
Key takeaways
Last Updated: Mar 27, 2024

Sessions framework in Django

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We can use client-side cookies to store valuable data for the web app. We can use client-side cookies to store various data valid for our web app. This leads to many security loopholes depending on the importance of the data we want to save.

Django offers a session framework for handling cookies for security reasons. Data is saved on the server-side (as in a database), and the client-side cookie has a session ID for identification. Sessions are also useful in avoiding situations when the user's browser is set to "deny all cookies."

Setting Up Sessions

The project settings are where you enable sessions in Django. In Python, add some lines to the INSTALLED APPS and MIDDLEWARE CLASSES options. This should be done when the project is created, but it's always good to be prepared, thus MIDDLEWARE CLASSES should have MIDDLEWARE CLASSES.

'django.contrib.sessions.middleware.SessionMiddleware'


And INSTALLED_APPS should have −

'django.contrib.sessions'

 

Django saves session information in the database (Django_session table or collection). Still, we can configure the engine to store information using other ways like: in a file or the cache.

When the session is enabled, every request (first argument of any Django view) has a session (dict) attribute.

Let's make a basic example to show how to create and store sessions.On a login page, let us keep the username in a cookie so, if not signed out, you won't see the login form when accessing our login page. Let's make the Django Cookies handling login system more safe by keeping cookies on the server.

First, let's alter our login view such that our username cookie is saved server-side.

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}

 

Then we'll make a formView view for the login form, which will hide the form if a cookie is set.

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', {})

 

Now we'll edit the url.py file to update the URL to match our new 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'))

 

we'll see the following screen when you go to /myapp/connection.

And then we will get redirected to the following page −

If you try to enter /myapp/connection again, you'll be taken straight to the second screen.

Let's make a straightforward logout view that clears our cookie

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

 

In myapp/url.py, match it with a logout URL.

url(r'^logout/', 'logout', name = 'logout'),

If you browse to /myapp/logout now, you'll see something like this: 

If you go back to /myapp/connection, you'll see the login form .

Some More Possible Actions Using Sessions

We've seen how to save and retrieve a session, but it's also worth noting that the request's session attribute includes a number of other important features, including:

  • set_expiry (value) − Sets the expiration time for the session.
  • get_expiry_age() − Returns the number of seconds until this session expires.
  • get_expiry_date() − Returns the date this session will expire.
  • clear_expired() − Removes expired sessions from the session store.
  • get_expire_at_browser_close() − Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed.

Frequently asked questions

  1. How can I get session data in Django?
    In the process, it also updates the cookie expiry time. session_data : Django stores the session data in the encoded format. To get the raw data, use the get_decoded() method of the session object.
     
  2. Where is data stored in Django?
    By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you're using these defaults. However, Django provides ways to write custom file storage systems that allow you to completely customize where and how Django stores files.
     
  3. How can we invalidate a session?
    To invalidate a session manually, call the following method: session. invalidate(); All objects bound to the session are removed.

Key takeaways

Django offers a session framework for handling cookies for security reasons. Data is saved on the server-side (as in a database), and the client-side cookie has a session ID for identification. Sessions are also useful in avoiding situations when the user's browser is set to "deny all cookies."

Django saves session information in the database (django_session table or collection). Still, we can configure the engine to store information using other ways like: in a file or the cache.

When the session is enabled, every request (first argument of any Django view) has a session (dict) attribute.

To know more about, check out our blogs : Django for loop templateDjango sign in confirmation email.

Happy learning!!

Live masterclass