Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store IP address in the database and django admin

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

like image 470
Radek Avatar asked May 05 '14 01:05

Radek


People also ask

Can I store IP address in database?

We can store an IP address with the help of INT unsigned. While using INSERT, include INET_ATON() and with SELECT, include INET_NTOA(). IP address is in dotted format.

How does Django save data to database?

Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

Is Django admin a database?

Django, by default, uses SQLite3 for development. SQLite3 is a simple relational database engine and your database is automatically created as db.


Video Answer


2 Answers

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() 
like image 114
ruddra Avatar answered Sep 23 '22 17:09

ruddra


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

like image 40
dhana Avatar answered Sep 21 '22 17:09

dhana