Answer the question
In order to leave comments, you need to log in
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
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):
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question