How to Use Geolocation in Django?

Published On: 19/12/2022 | Category: Django


Hi Dev,

This post will give you example of how to use geolocation in django. you can see how to create location-based app with geo django. Here you will learn django geolocation tutorial. In this article, we will implement a how to get geolocation in python django.

In this example utilising a third-party API that may deliver thorough geolocation information from a specific IP.

The Django web framework offers a number of methods for determining a user's geolocation. For constructing gis web apps or location-based applications, Django provides a number of packages devoted to IP lookup, IP geolocation, dealing with geographical information to compare locations on a map, calculate the distance between geographical points, and many other things.

Here i will give you we will help you to give example of how to use geolocation in django. So let's see the bellow example:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App
cd example
django-admin startapp core

Step 3: Update settings.py

Next, you need to add it in the settings.py file as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

Step 4: Get Started With the API

You must register for a free account and obtain an API key in order to access the rest API.

1. Click "Get Started" on the AbstractAPI Free IP Geolocation API webpage.

2. You will arrive at the API dashboard after registering or logging in, where you can find access to pricing and documentation as well as your API key.

3. We'll send a request to the AbstractAPI endpoint using the Python requests module and include our IP address in the request. The AbstractAPI URL and your API key must be taken from your API dashboard.

api_key = 'YOUR_API_KEY';

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

Step 5: Creating the Views

In this step, we need to create the views for performing fetch data from jsonplaceholder post api record.Open the core/views.py file and add:

core/views.py
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):
   print(ip_address)
   response = requests.get(api_url)
   return response.content

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)
   city = geolocation_data['city']
   region = geolocation_data['region']
   country = geolocation_data['country']

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

Step 6: Creating Urls

In this section, we’ll create the urls to access our views.Go to the urls.py core/urls.py file and update it as follows:

core/urls.py
from django.urls import path
from core import views

urlpatterns = [
    path('', views.home),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]

Step 7: Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000 address with a web browser.

I Hope It will help you....