Content:
IpInfo Setup
- Create an account at: https://ipinfo.io/
- Select API token from the side menu or go directly to: https://ipinfo.io/dashboard/token
- Copy the Token.
Getting the Data in Django
from django.urls import path
from .views import *
urlpatterns = [
path("", index.as_view(), name="index"),
]
class geoip(TemplateView):
template_name = "polls/index.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
ip = self.request.META.get('HTTP_X_FORWARDED_FOR')
if ip: ip = ip.split(',')[0].strip()
else: ip = self.request.META.get('REMOTE_ADDR', '8.8.8.8')
if ip in ("127.0.0.1", "::1"): ip = "8.8.8.8"
IPINFO_TOKEN = "xxxxxxx"
url = f"https://ipinfo.io/{ip}/json?token={IPINFO_TOKEN}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
loc = data.get("loc", "0,0").split(",")
location = {
'ip': data.get("ip"),
'city': data.get("city"),
'region': data.get("region"),
'country': data.get("country"),
'org': data.get("org"),
'latitude': loc[0],
'longitude': loc[1]
}
context['location'] = location
return context
<table>
<tr> <td>ip</td> <td>{{location.ip}} </td> </tr>
<tr> <td>city</td> <td>{{location.city}} </td> </tr>
<tr> <td>region</td> <td>{{location.region}} </td> </tr>
<tr> <td>country</td> <td>{{location.country}} </td> </tr>
<tr> <td>org</td> <td>{{location.org}} </td> </tr>
<tr> <td>latitude</td> <td>{{location.latitude}} </td> </tr>
<tr> <td>longitude</td> <td>{{location.longitude}} </td> </tr>
</table>
Django 5.2
23 Sept. 2025
|
Last Updated: 03 Dec. 2025
|
jaimedcsilva Related