我制作了函数,可以获取IP地址并在geoip2((中存储来自city_data的信息。我希望能够从city_data获得纬度和经度,并将其显示在我的HTML页面中。
我似乎要解决的问题是我无法调用用户会话模型中保存的任何信息。当我查看管理员以及打印QuerySets
时,信息就在那里。在模型中,我与Useressession/usersessessessessesmanager创建了一个新的会话,并与接收者一起保存该会话
models.py
from django.conf import settings
from django.db import models
from .signals import user_logged_in
from .utils import get_client_city_data, get_client_ip
class UserSessionManager(models.Manager):
def create_new(self, user, session_key=None, ip_address=None, city_data=None, latitude=None, longitude=None):
session_new = self.model()
session_new.user = user
session_new.session_key = session_key
if ip_address is not None:
session_new.ip_address = ip_address
if city_data:
session_new.city_data = city_data
try:
city = city_data['city']
except:
city = None
session_new.city = city
try:
country = city_data['country_name']
except:
country = None
try:
latitude= city_data['latitude']
except:
latitude = None
try:
longitude= city_data['longitude']
except:
longitude = None
session_new.country = country
session_new.latitude = latitude
session_new.longitude = longitude
session_new.save()
return session_new
return None
class UserSession(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
session_key = models.CharField(max_length=60, null=True, blank=True)
ip_address = models.GenericIPAddressField(null=True, blank=True)
city_data = models.TextField(null=True, blank=True)
city = models.CharField(max_length=120, null=True, blank=True)
country = models.CharField(max_length=120, null=True, blank=True)
latitude = models.FloatField(null=True, blank=True)
longitude = models.FloatField(null=True, blank=True)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = UserSessionManager()
def __str__(self):
city = self.city
country = self.country
latitude = self.latitude
longitude = self.longitude
if city and country and latitude and longitude:
return f"{city}, {country}, {latitude}, {longitude}"
elif city and not country and not latitude and longitude:
return f"{city}"
elif country and not city and not latitude and longitude:
return f"{country}"
return self.user.username
def user_logged_in_receiver(sender, request, *args, **kwargs,):
user = sender
ip_address = get_client_ip(request)
city_data = get_client_city_data(ip_address)
request.session['CITY'] = str(city_data.get('city', 'New York'))
# request.session['LAT_LON'] = str(lat_lon.get('latitude','longitude'))
session_key = request.session.session_key
UserSession.objects.create_new(
user=user,
session_key=session_key,
ip_address=ip_address,
city_data=city_data,
)
user_logged_in.connect(user_logged_in_receiver)
在此处,我在这里调用IP地址以及使用GEOIP2
存储的city_datautils.py
from django.conf import settings
from django.contrib.gis.geoip2 import GeoIP2
GEO_DEFAULT_IP = getattr(settings, 'GEO_DEFAULT_IP', '72.14.207.99')
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for is not None:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
ip_address = ip or GEO_DEFAULT_IP
if str(ip_address) == '127.0.0.1':
ip_address = GEO_DEFAULT_IP
return ip_address
def get_client_city_data(ip_address):
g = GeoIP2()
try:
return g.city(ip_address)
except:
return None
在这里,我对具有查询集的页面进行了视图,我测试了数据是否存在数据
视图
from django.shortcuts import render
from django.views.generic import TemplateView
from .models import UserSession, UserSessionManager
class LatlonView(TemplateView):
model = UserSession
template_name = 'analytics/latlon.html'
def get(self, request):
usersession = UserSession.objects.all()
print (usersession)
return usersession
我的假设是,这是问题所在的地方,我相信这是因为我可能会呼唤错误的事情,但是我尝试了我能想到的所有电话,并且无法获得正确的配置以完全显示任何数据
html
<!DOCTYPE html>
<html>
<head>
<title>Current Location</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
{% block body %}
<h1>{{ UserSession.city_data }}</h1>
<h1>{{ UserSession.latitude }}</h1>
<h1>{{ UserSession.longitude }}</h1>
<h1>HEllo<h1>
{% endblock %}
</body>
</html>
我相信我已经找到了解决方案。我将首先发布代码并在底部解释。
views.py
def get(self, request):
usersession = UserSession.objects.filter(user =self.request.user)
args = {'usersessions':usersession}
return render(request, self.template_name, args)
html
{% for usersession in in usersessions %}
whatever material you want to loop through
{% endfor %}
- HMTL需要知道要使用多少个或使用哪些用户。因此,必须运行循环才能获得某种列表
- 您需要从列表中调用特定对象,以便在views.py中在函数中。列表以及根据您的模型存储在其中的任何信息。
- 我还在查询上进行了过滤器,因此您可以在您的会话时获得最新的会话。这允许保存的会话是用户登录的,但我怀疑可以将其修改为您的喜欢。