django-ipgeo logo

django-ipgeo

akarca/django-ipgeo by us

IP geolocation for Django: resolves visitor IPs to city and country, optionally matched against your own models

0stars Python MIT last commit 6 hours ago
README.md

django-ipgeo

IP geolocation for Django. Resolves visitor IPs to city/country data and optionally matches them against your own database models.

Resolution order:

  1. Local MaxMind GeoLite2-City database — instant, no network call. Auto-downloaded and refreshed in the background when missing or stale.
  2. Remote APIs (sequential fallback) — 5 free services tried one-by-one; stops at the first successful response. Used while the local DB is unavailable or not configured.

Result is cached per IP in Django's cache framework — one lookup per address, shared across every visitor from it. Session storage is opt-in (USE_SESSION) and off by default: cookieless clients such as crawlers get a fresh session per request, so caching there writes a session row on every hit.

Features

  • Local MaxMind DB downloaded from a public mirror (no MaxMind key needed), refreshed weekly while running
  • Remote fallback to 5 free IP geolocation APIs (no API keys needed)
  • Session caching — one lookup per visitor, zero repeat calls
  • Generic model matching — attach geo results to any Django Country/City model
  • Context processor and optional middleware
  • Zero required external dependencies beyond Django (local DB needs geoip2)

Remote Fallback Services

Used only when the local DB is absent or returns no result.

Service Rate Limit API Key
ip-api.com 45 req/min No
ipwho.is Unlimited No
ipapi.co 30K/month No
freeipapi.com Unlimited No
ip2location.io 30K/day No

Installation

pip install git+ssh://git@github.com/akarca/django-ipgeo.git

Or in requirements.txt:

django-ipgeo @ git+ssh://git@github.com/akarca/django-ipgeo.git

For local MaxMind DB support, also install the geoip2 library:

pip install geoip2

Quick Start

1. Add to INSTALLED_APPS

INSTALLED_APPS = [
    ...
    "ipgeo",
]

2. Add the context processor

TEMPLATES = [
    {
        "OPTIONS": {
            "context_processors": [
                ...
                "ipgeo.context_processors.ipgeo_context",
            ],
        },
    },
]

3. Configure IPGEO in settings.py

Minimal config (remote-only, no local DB):

IPGEO = {
    "CONTEXT_PREFIX": "geo",
    "COUNTRY_MODEL": "myapp.Country",
    "CITY_MODEL": "myapp.City",
}

With local MaxMind DB and auto-download (from the ipaddress.world mirror, no key):

import os

IPGEO = {
    "CONTEXT_PREFIX": "geo",
    "COUNTRY_MODEL": "myapp.Country",
    "CITY_MODEL": "myapp.City",

    # Local MaxMind DB — recommended for production
    "LOCAL_DB_PATH": os.path.join(BASE_DIR, "geoip", "GeoLite2-City.mmdb"),
    # Optional: fallback to MaxMind when the mirror misses
    # "LOCAL_DB_LICENSE_KEY": os.environ.get("MAXMIND_API_KEY"),
}

4. (Optional) MaxMind license key

Only needed as a fallback when the mirror misses. Get a free key at maxmind.com and put it in .env as MAXMIND_API_KEY.

5. Use in templates

{% if geo_nearby %}
<h2>Tours Near You</h2>
{% if geo_city %}
    <p>Discover tours near {{ geo_city.name }}.</p>
{% elif geo_country %}
    <p>Popular tours in {{ geo_country.name }}.</p>
{% endif %}

{% for item in geo_nearby %}
    <a href="{{ item.get_absolute_url }}">{{ item.name }}</a>
{% endfor %}
{% endif %}

Settings Reference

All settings go inside the IPGEO dict in settings.py.

Engine settings

Key Default Description
TIMEOUT 2 Seconds per remote API call
USE_SESSION False Also mirror the result into the session. Off by default — see the caching note above.
SESSION_KEY "ipgeo" Session key used when USE_SESSION is on
CACHE_ALIAS "default" Which entry in CACHES holds the per-IP results
CACHE_TIMEOUT 86400 Seconds a successful lookup stays cached
CACHE_MISS_TIMEOUT 3600 Seconds a failed lookup stays cached, so unresolvable IPs don't re-run the remote fallback every request
CACHE_KEY_PREFIX "ipgeo:" Prefix for the per-IP cache keys

Local MaxMind DB settings

Key Default Description
LOCAL_DB_PATH None Absolute path to the .mmdb file. Downloaded automatically (mirror first) when missing or stale. Lookups that the DB places only at country level return city: "" instead of falling through to the remote APIs.
LOCAL_DB_LICENSE_KEY None MaxMind license key, used only when the mirror misses. Not required. To disable auto-download entirely set both this and CACHE_URL to None.
LOCAL_DB_EDITION "GeoLite2-City" MaxMind edition to download. Change to "GeoLite2-Country" for the country-only DB.
LOCAL_DB_UPDATE_DAYS 7 Re-download the DB after this many days. MaxMind releases updates twice a week; the mirror refreshes daily.
LOCAL_DB_CHECK_MINUTES 60 How often a running process re-checks the DB's age (a stat, no network), so long-lived workers refresh without a restart.
LOCAL_DB_RETRY_HOURS 6 After a failed download attempt, no process sharing LOCAL_DB_PATH (gunicorn workers, cron manage.py runs) tries again for this many hours. A file lock lets only one process download at a time.
CACHE_URL "https://www.ipaddress.world/api/geoip-cache/{edition}/" Public mirror checked before MaxMind. Set to None to disable. Avoids MaxMind's "Daily GeoIP Database Download Limit Reached" errors when many consumers run on the same MaxMind key.
CACHE_UPLOAD_TOKEN None Token required to PUT a fresh .mmdb to CACHE_URL after a successful MaxMind download. Set to None to skip the upload (read-only consumer).

Auto-download behaviour (cache-first):

  1. On Django startup (AppConfig.ready(), web processes only: manage.py commands other than runserver exit too soon and skip it) and then every LOCAL_DB_CHECK_MINUTES during lookups, if LOCAL_DB_PATH doesn't exist or is older than LOCAL_DB_UPDATE_DAYS days, a background daemon thread runs.
  2. It first tries CACHE_URL (a public mirror at ipaddress.world, which downloads every edition from MaxMind once a day). The file is accepted only if it carries the MaxMind DB metadata marker.
  3. On cache miss (404 / network error / non-mmdb payload) it falls back to MaxMind using LOCAL_DB_LICENSE_KEY, if set; otherwise the old file is kept and the next attempt is LOCAL_DB_RETRY_HOURS later.
  4. After a successful MaxMind download the new .mmdb is uploaded back to the mirror (if CACHE_UPLOAD_TOKEN is set) so the next consumer benefits.
  5. The .mmdb is placed at LOCAL_DB_PATH via os.replace() — atomic, so no request ever reads a partial file.
  6. While the first-time download is in progress (file absent), requests fall through to the remote API fallback transparently.
  7. While a refresh download is in progress (stale file present), requests continue to use the existing file until the new one lands.

Model matching settings

Key Default Description
COUNTRY_MODEL None Dotted model path, e.g. "myapp.Country". Set to None to skip country matching.
COUNTRY_MATCH see below Ordered list of match strategies for country lookup
CITY_MODEL None Dotted model path, e.g. "myapp.City". Set to None to skip city matching.
CITY_MATCH see below Ordered list of match strategies for city lookup
CITY_SELECT_RELATED [] Fields passed to select_related() on the city query
NEARBY_MODEL None Model for nearby items (typically same as CITY_MODEL)
NEARBY_FK_TO_COUNTRY None FK field name linking the nearby model to the country
NEARBY_FILTER {} Extra filter() kwargs for the nearby queryset
NEARBY_EXCLUDE {} Extra exclude() kwargs for the nearby queryset
NEARBY_SELECT_RELATED [] Fields passed to select_related() on the nearby query
NEARBY_LIMIT 6 Maximum number of nearby items returned
CONTEXT_PREFIX "ipgeo" Prefix for template variable names

Default COUNTRY_MATCH:

[
    {"field": "country_code", "lookup": "iexact", "geo_key": "country_code"},
    {"field": "name",         "lookup": "iexact", "geo_key": "country"},
]

Default CITY_MATCH:

[
    {"field": "name", "lookup": "iexact", "geo_key": "city"},
]

Each strategy dict:

Key Description
field Model field to filter on
lookup Django ORM lookup (e.g. iexact, exact)
geo_key Key from the geo result to use as the filter value. One of: city, country, country_code, lat, lon

Strategies are tried in order; the first one that returns a row wins.


Template Variables

The context processor exposes 4 variables. With CONTEXT_PREFIX = "geo":

Variable Type Description
geo_data dict or None Raw geo result: city, country, country_code, lat, lon, confidence, sources
geo_city model instance or None Matched city from your database
geo_country model instance or None Matched country from your database
geo_nearby list Nearby items filtered by NEARBY_FILTER

Middleware (Optional)

For access to raw geo data in views:

MIDDLEWARE = [
    ...
    "ipgeo.middleware.IPGeoMiddleware",
]
def my_view(request):
    if request.ipgeo:
        city = request.ipgeo["city"]
        country_code = request.ipgeo["country_code"]

The middleware only attaches raw geo data. Model matching is handled by the context processor.


Standalone Engine Usage

from ipgeo.engine import geolocate_ip, get_client_ip, is_private_ip

is_private_ip("192.168.1.1")  # True
is_private_ip("8.8.8.8")      # False

result = geolocate_ip("8.8.8.8")
# {
#     "city": "Mountain View",
#     "country": "United States",
#     "country_code": "US",
#     "lat": 37.386,
#     "lon": -122.0838,
#     "confidence": 1.0,
#     "sources": 1
# }

How It Works

  1. IP extraction — reads X-Forwarded-For, X-Real-IP, or REMOTE_ADDR
  2. Private IP check — skips lookups for localhost/private networks
  3. Per-IP cache — if the IP is already in the cache, returns immediately; negative results are cached too
  4. Local DB — if LOCAL_DB_PATH exists, queries the MaxMind .mmdb file (no network); returns on success
  5. Remote fallback — queries the 5 free APIs sequentially; stops and returns on the first successful response
  6. Auto-refresh — at startup and hourly while running, if the DB file is absent or older than LOCAL_DB_UPDATE_DAYS days, a background thread downloads and atomically replaces it

License

MIT