#django #python

In my blog, I wanted an easy way to count the number of views for a specific blog post without having to rely on Google Analytics. With the recent browser updates, libraries like Google Analytics are often disabled and shouldn't be relied on.

Therefor, I wanted a solution which does the count server-side and store them in the database.

The de-facto solution for doing this with Django is a module called django-hitcount. Getting it installed is the same as with every Django extension. We first use the pip utility to get the module installed:

1$ pip install django-hitcount

Then, we need to add it to the list of installed applications in the settings.py file of our app:


2    ...
3    'hitcount',
4    ...

I then updated the model class to allow sorting on the hitcount:


 1from django.db import models
 2from django.contrib.contenttypes.fields import GenericRelation
 4from hitcount.models import HitCountMixin, HitCount
 6class Post(models.Model, HitCountMixin):
 7    title = models.CharField(max_length=255, unique=True)
 8    slug = models.SlugField(max_length=255, unique=True)
 9    published_on = models.DateTimeField(blank=True, default=None, null=True)
10    content = models.TextField(blank=True)
12    hit_count_generic = GenericRelation(
13        HitCount, object_id_field='object_pk',
14        related_query_name='hit_count_generic_relation'
15    )
17    def current_hit_count(self):
18        return self.hit_count.hits

The GenericRelation allows you so query the posts sorting them by their hitcount:


The current_hit_count makes it easy to display the number of views in the template:


1{% if post.current_hit_count > 1 %}
2    | {{ post.current_hit_count }} views
3{% endif %}

Since I'm using class-based views for my blog detail pages, I can update the view to:


 1from .models import Post
 3from hitcount.views import HitCountDetailView
 5class PostDetail(HitCountDetailView):
 6    model = Post
 7    template_name = 'blog/post_detail.html'
 8    count_hit = True
10    def get_context_data(self, **kwargs):
11        context = super(PostDetail, self).get_context_data(**kwargs)
12        context.update({
13            'popular_posts': Post.objects.order_by('-hit_count_generic__hits')[:3],
14        })
15        return context

Instead of extending from DetailView, I'm now extending from HitCountDetailView instead. For the curious, HitCountDetailView is a combination of DetailView along with HitCountMixin which adds the hit counting capabilities.

To actually count the hits for this view, you need to add count_hit=True. This will count every time the view is rendered. I also added the get_context_data method so that I can add the list of popular posts to the blogpost detail page. To get these, I'm getting the posts ordered by their hit count in descending order, limiting the result to 3.

To show the related posts in your template, you can use:


1<h3>Popular Posts</h3>
2{% for p in popular_posts %}
3    <p>{{p.title}}</p>
4{% endfor %}

Last but not least, I wanted to add the view count to the list view of the blog posts in the admin view:


 1from .models import Post 
 3from django.contrib import admin
 5class PostAdmin(admin.ModelAdmin):
 6    list_display = ('title', 'formatted_hit_count',)
 8    def formatted_hit_count(self, obj):
 9        return obj.current_hit_count if obj.current_hit_count > 0 else '-'
10    formatted_hit_count.admin_order_field = 'hit_count'
11    formatted_hit_count.short_description = 'Hits'
13admin.site.register(Post, PostAdmin)

The complete documentation for Django hitcount can be found here.