如何使用 GeoIP2() django 模型从 IP 地址调用中提取保存的信息以显示在我的 html 中

How to pull information saved from IP address call with GeoIP2() django models to display in my html

我已经创建了从 GeoIP2() 中的 city_data 获取 IP 地址和存储信息的函数。我希望能够从 city_data 获取纬度和经度并将其显示在我的 html 页面中。

我似乎要解决的问题是我无法调用保存在用户会话模型中的任何信息。当我查看管理员以及打印查询集时,信息就在那里

在模型中,我使用 usersession/usersessionmanager 创建了一个新会话,并将该会话保存为接收器

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_data

Utils.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>

我相信我已经找到了解决办法。我会先post代码,在底部解释。

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 需要知道有多少或哪些 UserSession 到 use.So 循环必须 运行 才能获得某种列表
  • 您将需要调用列表中的特定对象,因此在 views.py 中的函数中,您可以将列表(在本例中我将其设置为 usersessionS)设置为 args* 然后您可以获得列表中的特定对象以及根据您的模型存储在其中的任何信息。
  • 我还对您的查询进行了过滤,因此您可以获得最近的会话,因为您的 session.This 允许保存的会话是用户登录的,但我怀疑可以根据您的喜好进行修改.