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 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/ .See this commits:

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(

    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 $ ./ makemigrations and then $ ./ migrate to apllying them in your database for model of Entry_Views in blog/

3. Change in your blog/ to make some condition to create or view your hit counter. See this commits:

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]
            ip = self.request.META.get("REMOTE_ADDR", "")
        return ip

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

            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]
                    if int(dns):
                        view = models.Entry_Views(entry=entry, 
                    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:

    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:

{{ tracking_hit_post }}

5. If you want to show it in your admin dashboard, you can add this in your blog/ .See this commit:

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

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

For more, you can chekout this commit:
Hope it usefull.

146 7 7 0