Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hit counter for pages in Django

Tags:

django

I want to have a page counter that displays the number of visitors who have viewed a particular page on my site. Is it possible to do this using Django?

like image 395
mohammadmonther Avatar asked Aug 04 '10 22:08

mohammadmonther


2 Answers

There's a Django app for that problem called django-hitcount. It's easy to use, and reusable in any of your projects.

like image 90
Ralph Avatar answered Oct 07 '22 01:10

Ralph


I know this is an old post but occasionally people might have the same question.

If you want to avoid a third party library and prevent the counter being updated at every page refresh you could do the following Mixin (building on S.Lott's answer)

class BlogPostCounterMixin(object):
    def get_context_data(self, **kwargs):
        context = super(BlogPostCounterMixin, self).get_context_data(**kwargs)
        blog_post_slug = self.kwargs['slug']
        if not blog_post_slug in self.request.session:
            bp = BlogPost.objects.filter(slug=blog_post_slug).update(counter=+1)
            # Insert the slug into the session as the user has seen it
            self.request.session[blog_post_slug] = blog_post_slug
    return context

It checks if the accessed model has been stored in the session. If it has been stored in the session, it skips incrementing, else it increments the counter and adds the slug of the model to the session preventing increments for page refreshes.

Note: This is a Mixin which you require to add into your view.

like image 21
IVI Avatar answered Oct 06 '22 23:10

IVI