Django standalone app - problem reading app settings in main project

I am using Django 3.2

I am writing a standalone app MyApp that uses GeoIP2

I want to be able to have a project using the MyApp app, to be able to do either one of the following.

  1. set GEOIP2_PATH in project.settings OR
  2. (default) fall back on the GEOIP2_PATH value set in MyApp.settings

This is what I have so far:

MyApp/settings.py

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
GEOIP_PATH = os.path.join(BASE_DIR, 'userprofile/geodata')

# ...

MyApp/utils.py

from django.conf import settings
from MyApp import settings as myapp_settings


def get_attribute_from_settings(attribute_name):
    try:
        value = getattr(settings, attribute_name)

    except AttributeError:
        try:
            value = getattr(myapp_settings, attribute_name)

        except AttributeError:
            raise ImproperlyConfigured()

    finally:
        return value 

Code that uses GeoIP2

from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception
from ipware import get_client_ip

geo = GeoIP2()


def do_something(address):
    # Barfs at next line: 
    info = geo.city(address)

When the function above is called, I get the following exception thrown:

raise GeoIP2Exception('GeoIP path must be provided via parameter or the GEOIP_PATH setting.') django.contrib.gis.geoip2.base.GeoIP2Exception: GeoIP path must be provided via parameter or the GEOIP_PATH setting

How can I use the get_attribute_from_settings() to get the default GEOIP2_PATH if not set in project.settings?

Back to Top