GeoIP tracking with IpInfo and Django

Content:

 

 

IpInfo Setup

 

 

 

 

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
  • Using ngrok with Django
  • Opening a Django project through a .exe file
  • Creating an online store with Django
  • CRUD
  • Creating a Basic Django Project Automatically
  • Filter Horizontal in a custom template
  • GeoIP tracking with IpInfo and Django
  • GeoIP tracking with MaxMind and Django
  • Django User Agents
  • Generating Temporary Download Links
  • Cython - Hiding the Code of a Django Project
  • Quick & Easy Django Deployment on PythonAnywhere
  • A Brief History of Django
  • Django & Paypal Webhooks
  • Generating QR Codes with Django

  • Buy Me a Coffee