0

How to Build Simple Django HIT Counter. Good night everybody, this night I wanna show how to build simply django hit counter for post. This method is what we doing in this Django Blog Python Learning.

This problem was asked for somebody in stackoverflow, but some different method, actually the popular plugin of django hit counter like https://github.com/thornomad/django-hitcounthttps://github.com/DirectlineDev/django-hitcounter or else, but in this problem, i just wanna build it with simply how to basicly i know how it works.

Tutorial we will create this time referring to the problem for Django Python Learning Blog v.2, we have previously shared source code of it.

However, you can use in your projects similar to this.

1. Create a model for saving your all record of hit counter. like this in your blog/models.py .See this commits: https://github.com/agusmakmun/Django-Blog-Python-Learning-v.2/commit/f94fa420500a398a500bd0c08497093dcd67d48b

import datetime

class Entry_Views(models.Model):
    entry = models.ForeignKey(Entry, related_name='entry_views')
    ip = models.CharField(max_length=40)
    session = models.CharField(max_length=40, null=True)
    created = models.DateTimeField(default=datetime.datetime.now())

    def __unicode__(self):
        return self.entry.title

    class Meta:
        verbose_name_plural = "Entry Views"

Note: entry = models.ForeignKey(Entry, related_name='entry_views') that relationship between entry and entry_views 

I don’t know why some problem we try it with different computer with different ip have no session_key, so in this field we change to null=Truesession = models.CharField(max_length=40, null=True)

2. Doing $ ./manage.py makemigrations and then $ ./manage.py migrate to apllying them in your database for model of Entry_Views in blog/models.py

3. Change in your blog/views.py to make some condition to create or view your hit counter. See this commits: https://github.com/agusmakmun/Django-Blog-Python-Learning-v.2/commits/master/update-1.1/blog/views.py

import datetime
from django.core.exceptions import ObjectDoesNotExist

class BlogDetail(generic.DetailView):
    model = models.Entry
    template_name = "post.html"

    def get_client_ip(self):
        ip = self.request.META.get("HTTP_X_FORWARDED_FOR", None)
        if ip:
            ip = ip.split(", ")[0]
        else:
            ip = self.request.META.get("REMOTE_ADDR", "")
        return ip

    def tracking_hit_post(self):
        entry = self.model.objects.get(pk=self.object.id)

        try:
            models.Entry_Views.objects.get(entry=entry, ip=self.get_client_ip(), session=self.request.session.session_key)
        except ObjectDoesNotExist:
                import socket
                dns = str(socket.getfqdn(self.get_client_ip())).split('.')[-1]
                try:
                    if int(dns):
                        view = models.Entry_Views(entry=entry, 
                                                  ip=self.get_client_ip(),
                                                  created=datetime.datetime.now(),
                                                  session=self.request.session.session_key)
                        view.save()
                    else: pass
                except ValueError: pass
        return models.Entry_Views.objects.filter(entry=entry).count()

    def get_context_data(self, **kwargs):
        context_data = super(BlogDetail, self).get_context_data(**kwargs)

        context_data['get_client_ip'] = self.get_client_ip
        context_data['tracking_hit_post'] = self.tracking_hit_post()
        return context_data

Some Explanations:
You can see, on this conditions:

try:
    models.Entry_Views.objects.get(entry=entry, ip=self.get_client_ip(), session=self.request.session.session_key)

It first try’ing to search your hit count rechord of Entry_Views with specific entryip and session_key, but if ObjectDoesNotExist it will automatically create to your database. and then it will showing with .count() method.

And then add self.tracking_hit_post() in your function of def get_context_data(self, **kwargs):

4. In your templates/post.html call context_data of hit counter to show and record. See this commit: https://github.com/agusmakmun/Django-Blog-Python-Learning-v.2/commit/11f25c6184d57093ab6c22aefdeca5b7e29bac09

{{ tracking_hit_post }}

5. If you want to show it in your admin dashboard, you can add this in your blog/admin.py .See this commit: https://github.com/agusmakmun/Django-Blog-Python-Learning-v.2/commit/475fba5ed31290c0908301223b03a997a3f79642

class Entry_Views_Admin(admin.ModelAdmin):
    list_display = ("entry", "ip", "session", "created")
    list_per_page = 20

admin.site.register(models.Entry_Views, Entry_Views_Admin)

for Example of it like this:Record of Django Hit Counter

For more, you can chekout this commit: https://github.com/agusmakmun/Django-Blog-Python-Learning-v.2/commits/master
Hope it usefull.

django python

Your Answer

blog comments powered by Disqus