B
B
Borodat Inzhenerovich2017-02-26 16:22:06
Django
Borodat Inzhenerovich, 2017-02-26 16:22:06

Simple and efficient way to count pageviews in django?

How can I count the number of page views/link clicks? There is a project - a blog with posts / publications - you need to display the number of views for the introduction of the category popular publications.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-02-26
@o3diev

I would do this:

class PageHit(models.Model):
    url = models.CharField(unique=True)
    count = models.PositiveIntegerField(default=0)

from functools import wraps
from django.db.models import F
from django.db import transaction

def counted(f):
    @wraps(f)
    def decorator(request, *args, **kwargs):
        with transaction.atomic():
            counter, created = PageHit.objects.get_or_create(url=request.path)
            counter.count = F('count') + 1
            counter.save()
        return f(request, *args, **kwargs)
    return decorator

from .decorators import counted

@counted
def some_view(request):
    ...

Demo project repository.
Or you can write a middleware that will do the same for all requests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question