1

I am trying to build a Django web application that will store internal tracking metrics (along with doing it's own work). I have so far created models to get API hit counters. I want to check from which location user accessed my application. For that purpose I have to store data in GeoDjango Model.

from django.contrib.gis.db import models

class AccessLocation(models.Model):
    location = g_models.PointField()
    user = models.ForeignKey(User,on_delete=models.PROTECT)
    class Meta:
        abstract = True
        db_table = "location_info"

Now I want to capture User's location when they access my views and store in data-base. Is there any django/pythonic way to do it? For eg: hidden form fields that captures user location (latitude and longitude)? EDIT: I have found how to fetch user's location (if they allow). The question is how do I store them in django model/form?

S Verma
  • 103
  • 2
  • 9
  • Possible duplicate of [Django, Retrieve IP location](https://stackoverflow.com/questions/2218093/django-retrieve-ip-location) – Dev Catalin Oct 07 '19 at 16:42

1 Answers1

1

You could use a user's IP address and https://ipstack.com/ for accessing a user's location information.

def get_client_ip(request):
   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')
   return ip


def get_geolocation_for_ip(ip):
    url = f"http://api.ipstack.com/{ip}?access_key={access_key_from_ip_stack}"
    response = requests.get(url)
    response.raise_for_status()
    return response.json()

geo_info = get_geolocation_for_ip(get_client_ip(request))
Vimm Rana
  • 86
  • 2
  • 10
  • Something to note-getting geolocation via IP is always at a best guess effort. IP geolocation at the country level is fairly reliable on some of these serivices like ipstack.com, ipfind.com etc. but becomes less reliable as you go further down to city level, postcode/zipcode level. IP geolocation is inherently a guessing game. I have found that some services may work well on some IP addresses and not so well on others. So always keep this in mind there's no one perfect service to use – Timothy Mugayi Oct 12 '20 at 07:59