DEV Community

Cover image for Using Django's hitcount for unregistered users in your application
Osahenru
Osahenru

Posted on

Using Django's hitcount for unregistered users in your application

Django hitcount is a python library that allows you track the number of hits/views on a particular objects by detecting the IP address of each click to prevent unreal views this ensures views aren't counted twice.

This library was built using the Django’s class based views which provides a wrapper for Django’s generic DetailView and allows you to process the Hit as the view is loaded.

To begin with this library you must have Python and Django running on your system, next we install the django-hitcount using pip install django-hitcount, after installation we add the hitcount library to our installed applications in settings.py

settings file

Next, we modify our models.py file by importing the following line of code

from hitcount.models import HitCountMixin, HitCount
from django.contrib.contenttypes.fields import GenericRelation
Enter fullscreen mode Exit fullscreen mode

this library was built using Django's class based views so for beginners who might have already began using function based view in their application should have no worry as you can use both function based views and a class based view in one application view.

So, now lets move to our views.py and tweak it a little, but before we do that, we need to import our hitcount into our views.py file

from hitcount.views import HitCountDetailView
Enter fullscreen mode Exit fullscreen mode

Detail views

The HitCountDetailView can be used to do the business-logic of counting the hits by setting count_hit=True.

Almost there, now we move to our HTML template and load our hitcount tags, just right above your html DOCTYPE load the hitcount tags

{% load hitcount_tags %}
Enter fullscreen mode Exit fullscreen mode

Finally, we add styling to our application with this line of code

<span class="ion-ios-eye"></span> {% get_hit_count for project %} views
Enter fullscreen mode Exit fullscreen mode

VOILA!!! You've successfully integrated Django's hitcount to your application

Top comments (2)

Collapse
 
sameerahmed123 profile image
sameer-ahmed123

what is the main use case for this library ?
social media sites??

Collapse
 
osahenru profile image
Osahenru

To track the number of views or click on a particular object...