4

I am trying to collect data for each visitor count related to every Page View Detail.

I have implemented the function which counts the visitors for the page but everytime it is refreshed it will add one more view which is not accurate data. My question is how to add to the function IP adress to show if it does exist the disregard it from the count and the visitor count is only related to new visitors.

Here is the models.py

class Post(models.Model):
    user= models.ForeignKey(User, on_delete=models.CASCADE)
    --------------------------------------------------
    title = models.CharField(max_length=100, unique=True)
    viewCount=models.IntegerField(default=0)

    def __str__(self):
        return self.title

    def incrementViewCount(self):
        self.viewCount += 1
        self.save()

Here is the views.py

    def get(self, request, *args, **kwargs):
        res = super().get(request, *args, **kwargs)
        self.object.incrementViewCount()
        return res
A_K
  • 731
  • 3
  • 15
  • 40
  • Well, user IP is in request object. https://stackoverflow.com/a/4581997/10187000 You could create a cache/file/db table where you keep IP and number of visits. Basicly a dict with key of IP and value counter Although I won't expect IP to be fixed for same user over days. Writing it as a class or decorator will help you making this feature for any page – Maks Jul 29 '20 at 07:48
  • I think csrf_token/json web token is unique to every user. As long as session remains active that can be a way to count number of users. – Vishesh Mangla Aug 03 '20 at 18:54

1 Answers1

6

You could either get the users IP and check whether or not the IP already has been counted for that day.

Getting an users IP address in Django:

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

You would then have to add a date-field and save the visit on an IP basis, i.e. you'd have rows with the columns IP, date -> then it's just a matter of counting how many distinct IPs you have for either that day (day count) or over all time.

e.g.

IP              | Date
239.123.191.194   2020-07-27
239.183.192.181   2020-07-27

Pseudo query -> Select count(IP) where Date = "2020-07-27" -> 2

Or you could look into django-tracking2 or https://github.com/thornomad/django-hitcount -> these libraries do all the things you need and more and are quite easy to implement.

alexisdevarennes
  • 5,437
  • 4
  • 24
  • 38