Get Visitor Location using GeoIP2 in Django

ArRosid
4 min readOct 11, 2019

--

In the previous story, I already show you how to get visitor IP Address & visitor detail information like OS used by visitor, browser used by visitor, and others in django project. If you haven’t read that story, You can read it first here

In this story, I will show you how to get Visitor location based on visitor IP Address. We will use existing code from my previous story. You can clone it from my github https://github.com/ArRosid/django-visitor-ip

The structure directory of the project will be like this

Above we can see that our project name is django_visitor_ip, and we have one django application named app.

Let’s start coding to get visitor location. First we need to install geoip2 package by typing this command

pip install geoip2

Next, we need to add geoip2 to INSTALLED_APP in settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
'django_user_agents',
'geoip2'
]

Now let’s migrate our django project

python manage.py migrate

Next steps, we need to download GeoIP2 database. You can download it from here https://dev.maxmind.com/geoip/geoip2/geolite2/

We need to download GeoLite2 City & GeoLite2 Country. After download that two file, extract it and place the extracted file inside geoip directory in our project. The structure directory will be like this

Now let’s edit settings.py file to tell django where we save the GeoIP2 database. Put this line of code in the end of settings.py

GEOIP_PATH =os.path.join('geoip')

Now our configuration for GeoIP2 is done! Now Let’s try to get location based on IP Address. We will use django shell first

Ahmads-MacBook-Air:$ python manage.py shell
Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.gis.geoip2 import GeoIP2
>>> from pprint import pprint
>>>
>>> g = GeoIP2()
>>> result = g.city('8.8.8.8')
>>> pprint(result)
{'city': None,
'continent_code': 'NA',
'continent_name': 'North America',
'country_code': 'US',
'country_name': 'United States',
'dma_code': None,
'latitude': 37.751,
'longitude': -97.822,
'postal_code': None,
'region': None,
'time_zone': 'America/Chicago'}

Cool!!! Now we can get Location information based on IP Address. Last step, let’s integrate this to our django project. Edit views.py file inside app directory

from django.shortcuts import render, HttpResponse
from django.contrib.gis.geoip2 import GeoIP2
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')

device_type = ""
browser_type = ""
browser_version = ""
os_type = ""
os_version = ""
if request.user_agent.is_mobile:
device_type = "Mobile"
if request.user_agent.is_tablet:
device_type = "Tablet"
if request.user_agent.is_pc:
device_type = "PC"

browser_type = request.user_agent.browser.family
browser_version = request.user_agent.browser.version_string
os_type = request.user_agent.os.family
os_version = request.user_agent.os.version_string

g = GeoIP2()
location = g.city(ip)
location_country = location["country_name"]
location_city = location["city"]
context = {
"ip": ip,
"device_type": device_type,
"browser_type": browser_type,
"browser_version": browser_version,
"os_type":os_type,
"os_version":os_version,
"location_country": location_country,
"location_city": location_city

}
return render(request, "home.html", context)

Edit home.html file like this

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Welcome Home!</h1>
<h3>You are visiting from :</h3>
<ul>
<li>IP Address : {{ip}}</li>
<li>Device: {{ device_type}}</li>
<li>Browser: {{browser_type}} {{browser_version}}</li>
<li>OS: {{os_type}} {{os_version}}</li>
<li>City: {{ location_city }}</li>
<li>Country: {{ location_country }}</li>

</ul>
</body>
</html>

Okay, now our code is done. Let’s run our django project

Ahmads-MacBook-Air:$ python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
October 11, 2019 - 22:47:16
Django version 2.2.6, using settings 'django_visitor_ip.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

This is what we will get when access it

Oh no!!! Why we got error?

Don’t worry, we get error because we access this server from 192.168.60.92 (IP Address of my laptop), and that address is Private Address, So GeoIP2 don’t know about this IP Address.

To test this project, we need to run our django project in the server with Public Address and access it from other device that connected to Internet.

In my case, I have server with IP Public, so I will run my django project on that server.

I already run my django project on my server with IP Public. To test it, I will access the server from my phone. In this case my phone is using cellular data.

Cool!!! Now we get Visitor Location based on their IP Address.

Tips: If you run this project in the server with IP Public, don’t forget to put the Public address in ALLOWED_HOST inside settings.py file

You can clone this project from my github https://github.com/ArRosid/django-visitor-ip

This is the end of this story. I am very excited to write another amazing story, so stay tune!!

--

--