I have a small question to ask you. I use GEO IP to locate my users and I would like to record this information every time user log in to improve the user experience of the app. The problem is that it doesn't save absolutely nothing at each connection. UserProfile models is empty...
Anyone has an idea about this?
user/middleware.py
from .models import UserProfile
from django.contrib.gis.geoip2 import GeoIP2
from django.utils.deprecation import MiddlewareMixin
class LastLoginInfo(MiddlewareMixin):
def geolocalisation(request):
if request.user.is_authenticated():
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')
device_type = ""
browser_type = ""
browser_version = ""
os_type = ""
os_version = ""
if request.user_agent.is_mobile:
device_type = "Mobile"
if request.user_agent.is_tablet:
device_type = "Tablet"
if request.user_agent.is_pc:
device_type = "PC"
browser_type = request.user_agent.browser.family
browser_version = request.user_agent.browser.version_string
os_type = request.user_agent.os.family
os_version = request.user_agent.os.version_string
g = GeoIP2()
location = g.city(ip)
location_country = location["country_name"]
location_city = location["city"]
#UserProfile.objects.update_or_create(user=request.user, defaults={'ip_address_ua': request.data['ip']})
UserProfile.objects.filter(user=request.user.pk).update(ip_address_ua=ip, device_ua=device_type, browser_ua=browser_type, os_device_ua=os_version, city_ua=location_city, country_ua=location_country)
main/settings.py
MIDDLEWARE = [
...
'user.middleware.LastLoginInfo',
...
]