我有一个小问题想问你。我使用 GEO IP 来定位我的用户,我希望在用户每次登录时记录此信息,以改善应用程序的用户体验。问题是它不会在每个连接上绝对保存任何内容。UserProfile 模型为空...
有人对此有什么想法吗?
用户/中间件.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)
主要/设置.py
MIDDLEWARE = [
...
'user.middleware.LastLoginInfo',
...
]
婷婷同学_
UYOU
相关分类