How to Track Page Views In Django Using Middleware

Application monitoring is an essential task when building and managing web applications. There exist several libraries and tools to monitor and track your application, however in this tutorial, we will see how to use Django’s build in middleware feature to track our page views.

Tracking Page views Using Django Middleware

A middleware in Django is a way to process requests and responses globally before they reach the view or after they leave the view. This is an important concept in Django and you can even see how it is used in the django settings MIDDLEWARE section. We will use this same idea to track our pages. Let us begin

Create a new file named middleware.py in your Django app folder and add the following code:

from django.core.cache import cache

class PageViewMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        path = request.path
        page_views = cache.get(path, 0) + 1
        cache.set(path, page_views)
        return response

This middleware increments the page view count for each request’s path and stores it in Django’s cache.

You will have to add the custom middleware to your Django project’s settings. In your settings.py file, add the following line to the MIDDLEWARE list:

MIDDLEWARE = [
    # ...
    'your_app_name.middleware.PageViewMiddleware',
    # ...
]

Replace your_app_name with the name of your Django app.

Now how do we access the page view count in our views or templates? To do so you can use the following code:

from django.core.cache import cache

page_views = cache.get(request.path, 0)

Or better still inside your views.py

from django.core.cache import cache
def analytics_view(request):
    page_views = cache.get(request.path, 0)
    context = {"page_views": page_views}
    return render(request, "analytics/analytics.html",context)

The above approach uses caching, however we can combine caching together with storing the results in a database so that we can use it later for more analytics.

In the context of tracking page views in a database, we can create a model to store the page views count and update it whenever a page is visited.
Here’s an example of how to create a model to store page views and use it in a function-based view:

  1. Create a model to store the page views in your models.py:
from django.db import models

class PageView(models.Model):
    path = models.CharField(max_length=255, unique=True)
    count = models.PositiveIntegerField(default=0)

    def __str__(self):
        return f"{self.path} - {self.count} views"

This model has a path field to store the URL path and a count field to store the number of views.

  1. Run migrations to create the database table for the PageView model:
python manage.py makemigrations
python manage.py migrate

Since we want to store our results in a database we will modify the PageViewMiddleware to use both the cache and the PageView model we created

We will update our middleware.py to import the PageView model and modify the PageViewMiddleware:

from django.core.cache import cache
from your_app.models import PageView

class PageViewMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        path = request.path

        # Check if the count is in the cache
        page_views = cache.get(path)

        if page_views is None:
            # If not in cache, get the count from the database and update the cache
            page_view, created = PageView.objects.get_or_create(path=path)
            page_views = page_view.count
            cache.set(path, page_views)

        # Increment the count in the cache and update the database
        page_views += 1
        cache.set(path, page_views)
        PageView.objects.filter(path=path).update(count=page_views)

        return response

This modified middleware first checks if the page views count is in the cache. If not, it retrieves the count from the PageView model in the database and updates the cache. Then, it increments the count in the cache and updates the PageView model in the database.

Now, the PageViewMiddleware uses both the cache and the PageView model to store and update the page views count.

This approach combines the benefits of caching such as reducing database queries and persisting data in the database in terms of reliability and query capabilities.

I hope this was helpful

Thank you for your time

Jesus Saves

By Jesse E.Agbe(JCharis)

Leave a Comment

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