pythonhtmldjangodjango-modelsgeoip2

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


I have made function that gets the IP address and stores information from the city_data in GeoIP2(). I want to be able to get the Latitude and longitude from the city_data and display it in my html page.

The problem i seem to be arriving at is that I am not able to call any of the information that is saved in the user session model. The information is there when i look at the admin as well as when i print out the querysets

In the models i create a new session with usersession/usersessionmanager and and save that session as with the receiver

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)

In here is where i call the IP address as well as the city_data that it stores with GEoIP2

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

Here i made a view for the page that has the query set i tested to see if the data is there

Views

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

My hypothesis is that here is where the problem lies I believe that its because I might be calling the wrong thing but I have attempted every call i can think of and not able to get the right configuration to show any data at all

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>

Solution

  • I believe I have found the solution. I will post the code first and explain at the bottom.

    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 %}