How to track number of hits/views for particular objects in Django | Django Packages Series #2
Tags: python, django, tutorial, beginners
Published: 2019-10-06 21:24:37

This post cross-published with [OnePublish](https://www.onepubli.sh)

<h3>What's up DEVs?</h3>
<p>Welcome to the second post of Django Packages Series. In this quick tutorial we are going to learn how to track number of views/hits for specific objects.</p>

<p>Tracking is really useful functionality. When user enters your application, number of views can attract user to click specific posts and read it. Also it's good to show users most popular posts.</p>

<p>I saw some solutions on internet related with this topic. Some of developers using <b>F()</b> expression to handle view count:</p>

```python
Post.objects.filter(pk=post.pk).update(views=F('views') + 1)
```
<h4>Bad Approach!</h4>
<p>By using F() and update views every time when user clicks on object is not good solution to create view counter. So, it will not count clicks properly, views will increase every time when same user clicks to same post.</p>
<p>Let me introduce you <b>django-hitcount</b>. Django-Hitcount allows you to track the number of hits (views) for a particular object. This isn’t meant to be a full-fledged tracking application or a real analytic tool; it’s just a basic hit counter.</p>
<p>Hitcounter will detect IPs and prevent from unreal views. So, views will count once for each specific user.</p>

<p>Create new Django project named "blog" and create app named "posts". Then run the following command to install the package.</p>

```
pip3 install django-hitcount
```

<p>Add django-hitcount to your INSTALLED_APPS:</p>
<b>settings.py</b>

```python
INSTALLED_APPS = (
    ...
    'hitcount'
)
```
<p>There are several strategies for using django-hitcount but in this tutorial I will show you the best way to implement it in your app. Now, let's create our models:</p>
<b>models.py</b>

```python
from django.db import models
from hitcount.models import HitCountMixin, HitCount
from django.contrib.contenttypes.fields import GenericRelation
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Post(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    published = models.DateField(auto_now_add=True)
    slug = models.SlugField(unique=True, max_length=100)
    hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk',
     related_query_name='hit_count_generic_relation')


    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        return super(Post, self).save(*args, **kwargs)
```

<p>You are not required to do anything specific with your models; django-hitcount relies on a <a href="https://simpleisbetterthancomplex.com/tutorial/2016/10/13/how-to-use-generic-relations.html">GenericForeignKey</a> to create the relationship to your model’s HitCount.</p>

<p>Then, let's create our views:</p>
<b>views.py</b>
```python
from django.shortcuts import render
from django.views.generic.list import ListView
from hitcount.views import HitCountDetailView
from .models import Post

class PostListView(ListView):
    model = Post
    context_object_name = 'posts'
    template_name = 'post_list.html'


class PostDetailView(HitCountDetailView):
    model = Post
    template_name = 'post_detail.html'
    context_object_name = 'post'
    slug_field = 'slug'
    # set to True to count the hit
    count_hit = True

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        context.update({
        'popular_posts': Post.objects.order_by('-hit_count_generic__hits')[:3],
        })
        return context
```
<p>The <b>HitCountDetailView</b> can be used to do the business-logic of counting the hits by setting count_hit=True. Also we can filter the most viewed posts as shown above.</p>

<p>Now, let's configure our urls:</p>
<b>urls.py</b>

```python
from django.contrib import admin
from django.urls import path, include
from posts.views import PostListView, PostDetailView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', PostListView.as_view(), name='posts'),
    path('<slug:slug>/', PostDetailView.as_view(), name='detail'),
    path('hitcount/', include(('hitcount.urls', 'hitcount'), namespace='hitcount')),
]
```
<p>To display total views for related object we will use <i>get_hit_count</i> template tag.</p>
<b>post_list.html</b>
```html
{% extends 'base.html' %}
{% load hitcount_tags %}

{% block content %}
  <h2>Posts List</h2>
  <ul>
    {% for post in posts %}
        <h3 class="mt-5"><a href='{% url "detail" post.slug %}'>{{post.title}}</a></h3>
        <p class="lead">{{post.description}}</p>
        <p>{{post.published}}</p>
        <p>Views: {% get_hit_count for post %}</p>
    {% endfor %}
  </ul>
{% endblock %}
```
<b>post_detail.html</b>

```html
{% extends 'base.html' %}
{% load hitcount_tags %}

{% block content %}
  <h2>{{post.title}}</h2>
  <ul>
        <p class="lead">{{post.description}}</p>
        <p>Published: {{post.published}}</p>
        <p>Views: {% get_hit_count for post %}</p>
  </ul>

  <h3>Popular Posts</h3>
  {% for p in popular_posts %}
  <p>{{p.title}}</p>
  {% endfor %}
{% endblock %}
```

<p>You can download or clone the project on my GitHub</p>
{% github raszidzie/Django-Hitcount-Tutorial %}

<p>That's it! Make sure you are following me on social media and please support me by <a href="https://www.buymeacoffee.com/xT2K0N1PY">buying me a coffee☕</a> so I can upload more tutorials like this. See you in next post DEVs!</p>

<a href="https://reversepython.net/">Reverse Python</a>
<a href="https://www.instagram.com/coderasha/?hl=en">Instagram</a>
<a href="https://twitter.com/coderasha?lang=en">Twitter</a>