I am trying to get the users device location. But the geoip2 returns a location far away from users location (almost 20km-25km). When I connect my device through a mobile network it shows a different location when I connect my device with the wifi
First I am getting the users ip
def get_ip(request):
xff = request.META.get('HTTP_X_FORWARDED_FOR')
if xff:
ip = xff.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR', None)
return ip
But this gets the users private ip and the private ip is not in the country or city datasets so the geoip2 throws an error.
So I try to get the public ip address through a website
def get_ip(request):
from requests import get
ip = get('https://api.ipify.org').text
if ip:
return ip
Now i use geoip2 to get the users location data
def home(request,):
....
....
....
....
from django.contrib.gis.geoip2 import GeoIP2
g = GeoIP2()
ip = get_ip(request)
print(ip)
country = g.country(ip)
city = g.city(ip)
print(country, city)
lat, long = g.lat_lon(ip)
print(lat, long)
...
...
...
Can you please suggest a better way or proper way to get the accurate location of the user?