Use django-hitcount to count hits/views of django project

created at 06-19-2021 views: 5

The django-hitcount package is very useful for counting hits or views for our django websites.

I like it because it enables us to count the hits with Ajax method (the HitCountJSONView), its advantage is:

it moves the business-logic to an Ajax View and hopefully speeds up page load times and eliminates some bot-traffic.

so, bellow I will show how I implemented this app into my django blog.

Install django-hitcount

pip install django-hitcount

add ‘hitcount' to your settings:

INSTALLED_APPS = [
    ...
    'hitcount',
]

and add path to urls.py:

urlpatterns = [
    ...
    path('hitcount/', include('stdworkflow.hitcount.urls', namespace='hitcount')),
 ]

and then execute migration to create tables in database:

python3 manage.py migrate hitcount

Front-end

the first thing is to load hitcount_tags in templates you want to use hitcount:

{% load static hitcount_tags  %}

bellow is an example you can use in your template(s) of a specific object (detail template of article, product, question and so on):

 <script src="{% static 'js/jquery.js' %}"  type="text/javascript"></script>
 <script src="{% static 'hitcount/jquery.postcsrf.js' %}"></script>
{% get_hit_count_js_variables for article as hitcount %}
<script type="text/javascript">
    jQuery(document).ready(function($) {
      $.postCSRF("{{ hitcount.ajax_url }}", { hitcountPK : "{{ hitcount.pk }}" });
    });
</script>
  • {% get_hit_count_js_variables for article as hitcount %}:replace article with your own object name.

note the sequence:

  1. jQuery
  2. jQuery.postcsrf.js
  3. getting and passing the ajax_url and object id

since 2 and 3 are based on jQuery, so jQuery must be loaded first.

Another thing should be noted is If you use self-host jQuery, try avoid putting jQuery.postcsrf.js together with jQuery into django compressor template tag, it will not work based on my experience, maybe the sequence changed. 

show counted results

its very easy to show the counted results, just put a {% get_hit_count for article %} to where your want to show the number of views. replace article with your own object name.

example:

views:<span class="info-detail">{% get_hit_count for article %}</span>

Debug

If your configuration not work, try to use view page sources function of browsers to check if ajax_url and hitcount.pk have been obtained like follow:

<script type="text/javascript">
    jQuery(document).ready(function($) {
      $.postCSRF("/hitcount/hit/ajax/", { hitcountPK : "9" });
    });
</script>
Please log in to leave a comment.