Working with Django Session

Table of Contents

Django Session

What is Django Session?

Imagine when you visit a website, your computer talks to the website’s computer using a language called HTTP. This language is a bit forgetful; it doesn’t remember past conversations. So, if a website wants to remember things about you, like your preferences or if you’re logged in, it needs a way to do that.
That’s where sessions come in. In simple terms, sessions are like a memory for websites. They help the website remember things about you. Django, which is a tool used for building websites, uses sessions to keep track of your information, like if you’re signed in or what you like on the site. It gives each visitor a special ID, like a secret code, so when you come back, it knows it’s you. This special ID is stored in a cookie on your computer. The actual details, like your preferences, are kept safe on the website’s computer. It’s like having a secret key that only you and the website know, so your information stays secure.
Django sessions give developers a simple way to manage session data in views and templates, making it easy to share data between different parts of the application. To sum up, Django sessions offer a secure and customized online experience by streamlining the handling of user-specific data. They facilitate easy communication between the client and the server, giving developers the tools they need to easily design dynamic online applications.
Cookies are sent and received by Django via the session middleware. When you first visit a website, the session middleware begins a new session. It creates a big, random number called a session identifier and gives it to your web browser as a cookie. In the following visits, the session middleware checks the sessionid value in the cookie from your web browser. It then matches it with the stored session identifier on the web server and connects the session data with your new requests.
django-sessions map

django-sessions
For security purposes, instead of storing important data directly in the cookie on the user’s computer, Django keeps that data safe on the server side, kind of like in a secret vault (usually in a database). The only thing the cookie on your computer has is a special ID that helps the server recognize you. So, it’s like having a key to a secret locker – the key is in your pocket (the cookie), but the important stuff is kept safe in the locker (on the server). This way, even if someone looks at your key, they can’t access the valuable information without the server’s permission. Sessions also come in handy if someone’s web browser doesn’t like cookies, as they still work without any issues.

Steps to use session in Django
Firstly, we need to make sure that our Django project has session support enabled before we start using sessions. To enable sessions, there are two actions to follow.

1. Add ‘django.contrib.sessions‘ to INSTALLED_APPS:

# settings.py

INSTALLED_APPS = [
# …
‘django.contrib.sessions’,
# …
]

2. Add ‘django.contrib.sessions.middleware.SessionMiddleware’ to MIDDLEWARE:

# settings.py

MIDDLEWARE = [
# …
‘django.contrib.sessions.middleware.SessionMiddleware’,
# …
]


Session support in your Django project is enabled with these configuration.

Selecting and Recovering a Session Value

Picking and getting back something saved in a session in Django is quite easy. Let me explain with an example:

Setting a Session Value: In Django, you can store information in sessions using a dictionary-like object. It’s like having a special box to keep things. Imagine we want to save a greeting message, like ‘Hello, Django Sessions!’. Here’s how you do it in Django code:

from django.shortcuts import render

def set_session(request):
# Save a greeting message in the session
request.session['greeting'] = 'Hello, Django Sessions!'
return render(request, 'session.html')

Now, whenever someone visits, we put ‘Hello, Django Sessions!’ in the special box under the name ‘greeting’.

Getting a Session Value: To get that saved greeting back, we can use a template. Think of a template like a magic spell to show things. Here’s an example template:

<!-- session.html -->

<!DOCTYPE html>
<html>
<head>
<title>Session Example</title>
</head>
<body>
<h1>Session Example</h1>
<p>Session Value: {{ request.session.greeting }}</p>
</body>
</html>

In this template, {{ request.session.greeting }} is like asking the magic box for the ‘greeting’. It shows the saved ‘Hello, Django Sessions!’ when the webpage is visited. So, setting and getting things from a session is like storing and retrieving treasures in a special box.

Example:

In a simple example, let’s make our library website greet the user with the count of their visits to the homepage. Open the file /locallibrary/catalog/views.py and add these lines into the index() function:

python
def index(request):
    # ...

    num_authors = Author.objects.count()  # The 'all()' is implied by default.

    # Number of visits to this view, as counted in the session variable.
    num_visits = request.session.get('num_visits', 0)
    request.session['num_visits'] = num_visits + 1

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
        'num_visits': num_visits,
    }

    # Render the HTML template index.html with the data in the context variable.
    return render(request, 'index.html', context=context)

Here, we track the number of visits using a session variable. Each time someone visits the page, the count increases and gets saved for their next visit. The num_visits value is then included in the context variable passed to the template.

Now, in your main HTML template (/locallibrary/catalog/templates/index.html), add this line at the bottom of the “Dynamic content” section:

html

<h2>Dynamic content</h2>


<p>The library has the following record counts:</p>
<ul><li><strong>Books:</strong> {{ num_books }}</li><li><strong>Copies:</strong> {{ num_instances }}</li><li><strong>Copies available:</strong> {{ num_instances_available }}</li>     <li><strong>Authors:</strong> {{ num_authors }}</li></ul><p>
You have visited this page {{ num_visits }} time{{ num_visits|pluralize }}.
</p>

This will display the count of visits to the page. Save your changes, restart the test server, and each time you refresh the page, the visit count should update.

Django Session Methods

Django’s session system comes with helpful methods to handle session variables. Let’s look at some of them:

  1. Setting a Session Variable:
    • request.session['username'] = 'JohnDoe'
    • This line sets a session variable named ‘username’ with the value ‘JohnDoe’. It’s like putting a label on a box and storing something inside.
  2. Getting a Session Variable:
    • username = request.session.get('username', 'Guest')
    • Here, we retrieve the value of the ‘username’ session variable. If it exists, we get its value (‘JohnDoe’). If not, the default value ‘Guest’ is used. It’s like looking into the labeled box to see what’s inside.
  3. Deleting a Session Variable:
    • request.session.pop('username')
    • This method removes the ‘username’ session variable. It’s like taking out what’s in the labeled box and leaving it empty.
  4. Clearing All Session Data:
    • request.session.clear()
    • This method wipes out all session data, making it like a brand new session. It’s like emptying all the labeled boxes, starting fresh.

These methods give you flexibility and control when dealing with session variables in Django Session, similar to managing and organizing things in labeled boxes.

Session expiry
By default, Django sessions end when you close your web browser. But, you can decide how long a session lasts by adjusting a setting. For instance, if you want sessions to stay active for 30 minutes, you’d set the timeout like this in your settings:

SESSION_COOKIE_AGE = 1800  # 30 minutes (in seconds)

That’s all! Now you have control over how long the Django sessions last in your web application. Just be cautious with session data, especially if it’s sensitive or linked to user logins.

Conclusion Django’s session

In this blog post, we explored how Django’s session framework works by showing a simple example of putting information into a session and taking it out. We also learned about some important session methods that help developers manage session information effectively. Additionally, we talked about the default settings for sessions in Django.

By using the session framework, you can make websites that remember things for users, like their preferences or items in a shopping cart. Django sessions are like a helpful tool that ensures user-specific information stays available across different visits to the website.

It’s crucial to keep user information safe, so always use sessions carefully and follow good practices for managing them. With Django’s session framework, you have the tools needed to create strong and interactive websites.

I hope this simplified version of the blog post helps you understand the example, session methods, and default settings for sessions in Django better.

 

Leave a Reply

Your email address will not be published. Required fields are marked *