[Fixed]-Django Project Wide logging of user ip

1👍

The best option for you is to write your own Middleware class

https://docs.djangoproject.com/en/1.8/ref/middleware/

It would look something like this:

class LogUserDetailsMiddleware(object):

    def process_request(self, request):
        print 'user: ' + request.user
        print 'ip-address: ' + request.META.get('REMOTE_ADDR')

Don’t forget to add your Middleware class to the MIDDLEWARE_CLASSES in your settings.py, after the AuthenticationMiddleware (so request.user excists)

0👍

I made this does it for me

class SetRemoteAddrFromForwardedFor(object):
    def process_request(self, request):
        try:
            real_ip = request.META['HTTP_X_FORWARDED_FOR']
        except KeyError:
            pass
        else:
            # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
            # Take just the first one.
            real_ip = real_ip.split(",")[0]
            #request.META['REMOTE_ADDR'] = real_ip
        if request.user.is_authenticated():
            email = request.user.email
            user_id = request.user.id
        else:
            email,user_id = "",""
        today = datetime.date.today()
        try:
            user = UserLog.objects.get(ip=real_ip, date=today, email=email)
        except:
            user = UserLog(ip=real_ip, email=email, user_id=user_id)
        if user.visits:
            user.visits +=1
        else:
            user.visits = 1
        user.save()
        log = LogTime(page=user)
        log.save()

class LogTime(models.Model):
    page = models.ForeignKey('UserLog', related_name="times",)
    time = models.TimeField(auto_now=True, blank=True)

    class Meta:
        ordering = ['page', 'time',]
        verbose_name = 'Log Time'
    def __unicode__(self):
        return self.page

class UserLog(models.Model):
    date = models.DateField(default=datetime.date.today(), blank=True, null=True)
    ip = models.CharField(max_length=100, blank=True, )
    email = models.CharField(max_length=100, blank=True, )
    user_id = models.CharField(max_length=100, blank=True, )
    visits = models.IntegerField(default=1, blank=True, null=True)


    class Meta:
        ordering = ['visits','date']
        verbose_name = 'User Log'
    def __unicode__(self):
        return "{0} {1}: {2} Visits Today: {3}".format(self.date, self.ip, self.email, self.visits)

Leave a comment