Question

Would like to store IP address of everybody who is coming to the site. What is the best approach to do this. Lets say have model

class ip(models.Model):
    pub_date = models.DateTimeField('date published')
    ip_address = models.GenericIPAddressField()

What would be the code in models or in views or somewhere that I would save it in the database also would like to save it with user-agent info similar to this.

django-admin-ip

Was it helpful?

Solution

In views.py:

views.py:

    ....

    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

    if x_forwarded_for:
        ipaddress = x_forwarded_for.split(',')[-1].strip()
    else:
        ipaddress = request.META.get('REMOTE_ADDR')
    get_ip= ip() #imported class from model
    get_ip.ip_address= ipaddress
    get_ip.pub_date = datetime.date.today() #import datetime
    get_ip.save()

OTHER TIPS

I have gave the example from @Sahil Kalra using middleware,

Model:

class IpAddress(models.Model):
    pub_date = models.DateTimeField('date published')
    ip_address = models. GenericIPAddressField()

Middleware:

import datetime

class SaveIpAddressMiddleware(object):
    """
        Save the Ip address if does not exist
    """
    def process_request(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[-1].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')
        try:
            IpAddress.objects.get(ip_address=ip)
        except IpAddress.DoesNotExist:             #-----Here My Edit
              ip_address = IpAddress(ip_address=ip, pub_date=datetime.datetime.now())
              ip_address.save()
            return None

Save the middleware some place in your project folder and In settings file add this middleware. Here is reference How to set django middleware in settings file

You can fetch IP Address very easily into your views.py.

def get_ip_address(request):
    """ use requestobject to fetch client machine's IP Address """
    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')    ### Real IP address of client Machine
    return ip   


def home(request):
    """ your vies to handle http request """
    ip_address = get_ip_address(request)

As you want to save the user agent irrespective of the URL or View which is being called it doesn't make any sense to write this code in the Views or Models.

You should write a Middleware that would do the work for you. See more about Django middleware : https://docs.djangoproject.com/en/1.6/topics/http/middleware/

You want to over-ride the process_request() method of your custom middleware to get the IPaddress and useragent from request object and store it in IP model

The above link will give you absolute clarity about what to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top