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.
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.
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.
Django, by default, uses SQLite3 for development. SQLite3 is a simple relational database engine and your database is automatically created as db.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With