Guides
Last Updated Aug 03, 2023

Django Geolocation

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
IP Geolocation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Geolocation is the process of determining geographical location (i.e. something’s position on the Earth) using data that’s available on the internet (something like an IP address, for example.) There are many reasons you might want to do geolocation in an application—to show the user their position on a map, to provide them with localized content like translations and currency conversions, or to make sure that the user is who they say they are.

There are several ways to determine a user’s geolocation using the Django web framework. Django has several packages dedicated to IP lookup, IP geolocation, and working with geospatial data to compare places on a map, determine the distance between geographical points, and many other things useful for building gis web applications or a location app.

In this tutorial, we’ll look at basic IP geolocation with Django, using a third-party API that can provide detailed geographic data from a given IP. This tutorial assumes no familiarity with Django and can be completed by a beginner. You will need some familiarity with Python, the terminal, and a code editor (PyCharm or VS Code are good options.)

Let’s send your first free
API
IP Geolocation API
call
See why the best developers build on Abstract
Get your free api

Getting Started With Django

In order to use Django, you’ll need to have a Python installation on your machine. We recommend Python3. We’ll also be using a virtual environment to run the Django app. We’ll explain a bit about what a virtual environment is, but if you want more information, check out this guide.

Spin Up a Virtual Environment

The first thing we’ll do is create a project directory and spin up an environment inside it. It’s easiest to keep your virtual environments inside the same folder as your projects to make it easier to know which environment goes with which project.

What Is a Virtual Environment?

A virtual environment is like a container for your Python or Django application. It’s similar to a Docker container. It keeps all your project dependencies and Python installations for a particular contained in one place without affecting the global scope of the machine that runs the application. You can run multiple different virtual environments on one machine, each with its own version of Python and different versions of various dependencies.

Keeping these dependencies in their own containers means the versions and all the packages remain separate.

Run the following commands to get started



$ mkdir django-geo

$ cd django-geo

$ python3 -m venv venv

$ source venv/bin/activate

 Let’s quickly break down what each of these commands does.



$ mkdir django-geo

$ cd django-geo

Creates a new project directory and navigates into it.



$ python3 -m venv venv

Uses the Python3 installation (you can use Python or Python2 if you prefer) to create a new environment. The -m argument tells Python to use a particular module, and the first venv argument is the module we tell it to use. 

The second venv argument tells Python what to call the folder that the environment information will be stored in. You can call this anything you want, but venv is standard and will make it easier for other people who look at your code to know what it is right away.



$ source venv/bin/activate

This activates the environment inside the current shell. Once you run this command, you should see the following output in your terminal



$ (venv)

That indicates that you are inside the environment. Great! Now it’s time to install our dependencies.

Install Dependencies With Pip

Pip is Python’s package manager, similar to NPM or Yarn for Node. When we install packages inside the environment, they will only exist within that environment. For this project, we’ll only need django.

Make sure you are inside your environment and inside the project directory, then run the following command.



$ pip install django

Create a New Django Project

We’ll use the django-admin command line utility to create a new Django app. This utility comes with Django, so it should work now that you’ve installed it.



$ django-admin startproject DjangoIPGeolocation

This will create a new Django project inside your project directory, next to your venv environment folder. Name the project the same as the parent project directory. Open the project in your favorite code editor or IDE (VS Code is a good one) to start.

Create a New Django Application

The last setup step in getting up and running is to create a new application. Django projects are made up of many “apps.” You might break your project into several apps if it does a few different things. For example, you might have one app to handle authentication and sign-in. You might have another app to handle notifications, and another to manage the primary logic of rendering views and flows.

For now, we’ll just have one very simple app that renders a webpage where we can view geolocation information about IP addresses. Run the following commands to create that app inside your project.



$ cd DjangoIPGeolocation

$ python3 manage.py startapp geolocation

The manage.py startapp command tells Python to start up an app called geolocation. If the app doesn’t exist, it will be created.

Register the Geolocation App With the Main Django Project

In order for the main project to know that the app exists, it must be installed in the main project’s settings.py file. Open that file in your editor and add a line to the INSTALLED_APPS array.



# Application definition

 

INSTALLED_APPS = [

   'django.contrib.admin',

   'django.contrib.auth',

   'django.contrib.contenttypes',

   'django.contrib.sessions',

   'django.contrib.messages',

   'django.contrib.staticfiles',

   'geolocation'

]

For reference, here is what your project structure should look like now.

Create a Basic Django View

A Django view tells Django how to render the information. Let’s create a simple view that just returns some text about our Http Response.

Add the following the views.py file inside the geolocation application directory.



from django.shortcuts import render, HttpResponse

 

# Create your views here.

from django.shortcuts import render, HttpResponse

def home(request):

   return HttpResponse("Welcome!")

When a user requests the page that renders this view, it will simply return a string of text that says “Welcome!” In most cases, your Django application will also include an HTML template that the view will render. For our purposes, however, we don’t need one.

Next, let’s tell Django what URL we would like to render this view at.

Render the View at a URL

Create a file called urls.py inside the geolocation app directory. There is already a urls.py file inside the DjangoIPGeolocation main application folder, but we’re not using that file. We’ll come to that in a moment.

Add the following to geolocation/urls.py.



from django.urls import path

from . import views

urlpatterns = [

   path('', views.home),

]

This tells Django that inside the geolocation app, at the root path of the URL, we should render the home view that we just created.

Next, we need to tell the main DjangoIPGeolocation application to render the geolocation app at a particular URL. Open the urls.py file inside the main DjangoIPGeolocation directory and add the following.



from django.contrib import admin

from django.urls import path, include

 

urlpatterns = [

   path('admin/', admin.site.urls),

   path('', include("geolocation.urls"))

]

You’ll notice that the only things we actually added here are the include import, and the new path variable inside the urlpatterns array. This will tell Django to render our geolocation app at the root path of the main application.

Let’s run the application and take a look at the page in the browser.



$ python3 manage.py runserver

You will see a warning in the terminal that you have unapplied migrations. Don’t worry about this for now. Visit localhost:8000 in the browser to see your application.

Great! Our application is up and running.

Finding an IP

Next, we want to grab the IP address of the user who is visiting our site. We’ll use the IP to get geolocation information about the user.

Open up the views.py file inside the geolocation app and update it with the following code.



from django.shortcuts import render, HttpResponse

 

# Create your views here.

from django.shortcuts import render, HttpResponse

def home(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 HttpResponse("Welcome! 
You are visiting from: {}".format(ip))

Let’s quickly break down what this does.

The HTTP_X_FORWARDED_FOR header is metadata on the incoming request that contains the IP address that the request was originally sent from. We can pull the header off the incoming request by accessing the META field of the request. Then, we pull the IP out by splitting the HTTP_X_FORWARDED_FOR header string.

In case there is no IP address in the HTTP_X_FORWARDED_FOR header, we fall back to using the REMOTE_ADDRESS header instead, which should contain the IP of the most recent proxy that handled the request.

Go back to localhost: 8000 to see the IP rendered. Because we are doing local development, we see the loopback address, or localhost address, or 127.0.0.1.

Getting Geolocation Information From an IP Address

Now that we are getting the IP, we can use the Django rest framework and the AbstractAPI Free IP Geolocation API to get geographical information about the user. We can send the IP address that we pull from the incoming request to the API, and get back a JSON object from the rest API with the following information.



{

  "ip_address": "xx.xxx.xxx.xxx",

  "city": "XXxxx",

  "city_geoname_id": XXXXXXXX,

  "region": "California",

  "region_iso_code": "CA",

  "region_geoname_id": 5332921,

  "postal_code": "XXXXX",

  "country": "United States",

  "country_code": "US",

  "country_geoname_id": 6252001,

  "country_is_eu": false,

  "continent": "North America",

  "continent_code": "NA",

  "continent_geoname_id": 6255149,

  "longitude": XX,

  "latitude": XX,

  "security": {

    "is_vpn": false

  },

  "timezone": {

    "name": "America/Los_Angeles",

    "abbreviation": "PDT",

    "gmt_offset": -7,

    "current_time": "09:38:49",

    "is_dst": true

  },

  "flag": {

    "emoji": "🇺🇸",

    "unicode": "U+1F1FA U+1F1F8",

    "png": "https://static.abstractapi.com/country-flags/US_flag.png",

    "svg": "https://static.abstractapi.com/country-flags/US_flag.svg"

  },

  "currency": {

    "currency_name": "USD",

    "currency_code": "USD"

  },

}

I’ve redacted some of the information for privacy’s sake.

Get Started With the API

In order to use the rest API, you’ll need to sign up for a free account and get an API key.

Acquire an API Key

Go to the AbstractAPI Free IP Geolocation API homepage and click on "Get Started."

Once you’ve signed up or logged in, you’ll land on the API’s dashboard, where you’ll see your API key and links to documentation and pricing.

Send the IP Address to the Rest API

We'll use the Python programming language requests module to send a request to the AbstractAPI endpoint, passing it our IP address. You'll need to grab your API key and the AbstractAPI URL from your API dashboard.



api_key = 'YOUR_API_KEY';


api_url = 'https://ipgeolocation.abstractapi.com/v1/?api_key=' + api_key

Inside your views.py file, import the requests module and write a function called get_ip_geolocation_data that accepts an IP address as a parameter and sends it to the API. 



import requests


api_key = 'YOUR_API_KEY';

api_url = 'https://ipgeolocation.abstractapi.com/v1/?api_key=' + api_key


get_ip_geolocation_data(ip_address):


    response = requests.get(api_url + "&ip_address=" + ip_address)

    print(response.content)

Now, call the function after you pull the IP address out of the incoming request. When you visit localhost:8000, the view will send the request to the API and print the output in your terminal.

Unfortunately, all you’ll see is the following information.



b'{"ip_address":"127.0.0.1","city":null,"city_geoname_id":null,"region":null,"region_iso_code":null,"region_geoname_id":null,"postal_code":null,"country":null,"country_code":null,"country_geoname_id":null,"country_is_eu":null,"continent":null,"continent_code":null,"continent_geoname_id":null,"longitude":null,"latitude":null,"security":{"is_vpn":false}}'

Why is that? Well, the address we just sent to the API is the loopback address (127.0.0.1), which can’t be traced to any particular geographical location. Every computer has the same loopback address. The loopback address can’t uniquely identify a machine to the network.

So, for the purposes of this tutorial, we’re going to bypass sending the address that we pulled from the incoming request, and instead, simply send the public IP address of our machine. To do that, all we need to do is remove the ip_address parameter from the query string when we send our request to the API.

Rewrite the get_geolocation_data function to the following



def get_ip_geolocation_data():

 

   response = requests.get(api_url)

   print(response.content)

When the API receives a request with no IP address passed, it falls back to using the IP address of the machine that sent the request. Keep in mind that this will not work in production, because you are simply sending the IP address of the machine that is hosting the application, not the IP address of the user who is accessing the application. For testing, however, this works fine.

Visit localhost:8000 again and check out the new output in the console.



b'{"ip_address":"XX.XXX.XXX.XXX","city":"XXX","city_geoname_id":XXX,"region":"California","region_iso_code":"CA","region_geoname_id":XXXXXX,"postal_code":"XXXXX","country":"United States","country_code":"US","country_geoname_id":6252001,"country_is_eu":false,"continent":"North America","continent_code":"NA","continent_geoname_id":6255149,"longitude":XX.XXX,"latitude":XX.XXX,"security":{"is_vpn":false},"timezone":{"name":"America/Los_Angeles","abbreviation":"PDT","gmt_offset":-7,"current_time":"09:58:32","is_dst":true},"flag":{"emoji":"\xf0\x9f\x87\xba\xf0\x9f\x87\xb8","unicode":"U+1F1FA U+1F1F8","png":"https://static.abstractapi.com/country-flags/US_flag.png","svg":"https://static.abstractapi.com/country-flags/US_flag.svg"},"currency":{"currency_name":"USD","currency_code":"USD"},"connection":{"autonomous_system_number":7922,"autonomous_system_organization":"COMCAST-7922","connection_type":"Cable/DSL","isp_name":"Comcast Cable Communications","organization_name":"Comcast IP Services, L.L.C."}}'

Again, I’ve redacted some information.d

Render the User’s Location Information

Now we just need to add the information to the string that renders in the browser. We will need to parse the incoming data from JSON into a format that Python can read. To do that, we’ll use the json module. This will turn the response data into a dict. We can then access fields on that dict using square bracket notation.

Update views.py with the following code.



# Create your views here.

from django. shortcuts import render, HttpResponse

import requests

import json

 

api_key = 'YOUR_API_KEY'

api_url = 'https://ipgeolocation.abstractapi.com/v1/?api_key=' + api_key

 

def get_ip_geolocation_data(ip_address):

   # not using the incoming IP address for testing

   print(ip_address)

 

   response = requests.get(api_url)

   return response.content

 

from django.shortcuts import render, HttpResponse

def home(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')

 

   geolocation_json = get_ip_geolocation_data(ip)

   geolocation_data = json.loads(geolocation_json)

   country = geolocation_data['country']

   region = geolocation_data['region']

  

   return HttpResponse("Welcome! 
Your IP address is: {} and you are visiting from {} in {}".format(ip, region, country))

Head back to localhost:8000 in your browser to check out the new information.

Neat! We’ve used the user’s IP address to look up their geographical information.

Conclusion

In this tutorial, we learned how to get started with Django and make API calls to the AbstractAPI Free Geolocation API. We built a basic application that  uses a user’s IP address to determine the user location and show them information about their location.

The next step of this process would be to render the information inside a template, which would allow us to add more style to the webpage.

FAQs

What is Geo Django?

GeoDjango is a framework for working with geographic data in Django. It allows you to do things like finding the distances between two points on a map, finding areas of polygons, the points within a polygon, etc. For doing basic geolocation lookup, such as from an IP, GeoDjango is a bit overkill. You can use any third-party API or a smaller, more basic package like django-ip-geolocation to do this.

How Do I Use Google Maps in Django?

Django provides a package that integrates with the Google Maps API. The package is called django-google-maps and provides basic hooks into the Google Maps v3 API. The package allows you to create models that accept address and geolocation information and then renders them on a Google map.

What library do you need to work with geolocation in Django and Python?

There are several libraries that can do geolocation for both Django and Python. For Django, these include django-ip-geolocation, GeoDjango, and Django GeoIP2. Python can do geolocation from an IP address using the GeoPy or geolocation-python packages.

You can also use third-party APIs such as the AbstractAPI Free Ip Geolocation API to lookup geolocation information for a specific IP address.

4.9/5 stars (9 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
IP Geolocation API
API
key now
Abstract's IP Geolocation API comes with libraries, code snippets, guides, and more.
get started for free

Related Articles

Get your free
API
IP Geolocation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required