25👍
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()
12👍
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
- [Django]-How to show related objects in Django/Admin?
- [Django]-Force django-admin startproject if project folder already exists
- [Django]-Why is run called twice in the Django dev server?
6👍
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)
- [Django]-How can reference the last item in a list in a Django template? {{ list.-1.key }}
- [Django]-Cache_page with Class Based Views
- [Django]-Set Django IntegerField by choices=… name
3👍
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.
- [Django]-Change the width of form elements created with ModelForm in Django
- [Django]-Djangorestframework: Filtering in a related field
- [Django]-Django and Bootstrap: What app is recommended?