[Fixed]-How to access a python module variable using a string [ django ]

10👍

You can use import_module to load a module relative to the root of a django project.

from django.utils.importlib import import_module
app_label = "app"
url = import_module("%s.urls" % app_label).HOME_URL 

This should work within your django project, or in ./manage.py shell.

16👍

If you’re using Django 1.7+, you should use import_string instead.

from django.utils.module_loading import import_string
app_label = "app"
url = import_string("%s.urls.HOME_URL" % app_label)

By the way, some clarifications about Python modules and packages.

A package is a folder containing files, including one file called __init__.py. It sounds your ‘app’ ‘module’ is actually a package.

A module is a .py file within a package. So your urls.py is actually a module.

Leave a comment