django-hitcount Documentation, Release 1.3.0
UpdateHitCountResponse(hit_counted=Boolean, hit_message='Message'). hit_counted
will be True if the hit was counted and False if it was not. hit_message will indicate by what means the Hit
was either counted or ignored.
It works like this.
from hitcount.models import HitCount
from hitcount.views import HitCountMixin
# first get the related HitCount object for your model object
hit_count = HitCount.objects.get_for_object(your_model_object)
# next, you can attempt to count a hit and get the response
# you need to pass it the request object as well
hit_count_response = HitCountMixin.hit_count(request, hit_count)
# your response could look like this:
# UpdateHitCountResponse(hit_counted=True, hit_message='Hit counted: session key')
# UpdateHitCountResponse(hit_counted=False, hit_message='Not counted: session key has
˓→active hit')
To see this in action see the views.py code.
2.1.2 HitCountJSONView
The hitcount.views.HitCountJSONView can be used to handle an AJAX POST request. Django-hitcount
comes with a bundled jQuery plugin for speeding up the $.post process by handling the retrieval of the CSRF token
for you.
If you wish to use the HitCountJSONView in your project you first need to update your urls.py file to include
the following:
# urls.py
urlpatterns = [
...
url(r'hitcount/', include('hitcount.urls', namespace='hitcount')),
]
Next, you will need to add the JavaScript Ajax request to your template. To do this, use the {%
get_hit_count_js_variables for post as [var_name] %} template tag to get the ajax_url and
hitcount_pk for your object. The hitcount_pk is needed for POST-ing to the HitCountJSONView.
Here is an example of how all this might work together with the bundled jQuery plugin. It is taken from the example
project and the jQuery can be modified to suit your needs. In the example below it simply updates the template with
the HitCountJSONView response after the Ajax call is complete.
{% load staticfiles %}
<script src="{% static 'hitcount/jquery.postcsrf.js' %}"></script>
{% load hitcount_tags %}
{% get_hit_count_js_variables for post as hitcount %}
<script type="text/javascript">
jQuery(document).ready(function($) {
// use the template tags in our JavaScript call
$.postCSRF("{{ hitcount.ajax_url }}", { hitcountPK : "{{ hitcount.pk }}" })
.done(function(data){
$('<i />').text(data.hit_counted).attr('id','hit-counted-value').appendTo('#hit-
˓→counted');
(continues on next page)
6 Chapter 2. Installation and Usage