Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a django application, with a module called "app"
Now this module has a file called "urls.py" which has a variable called "HOME_URL"

What I'm trying to do ?

app_label = "app"
url = __import__(app_label).urls.HOME_URL
print url

That obviously doesn't work, but I hope you got what I'm trying to do, If not please comment I will edit the question to contain more info.

like image 895
Akamad007 Avatar asked Aug 19 '11 13:08

Akamad007


Video Answer


2 Answers

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.

like image 184
Shawn Chin Avatar answered Oct 19 '22 15:10

Shawn Chin


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.

like image 25
seddonym Avatar answered Oct 19 '22 15:10

seddonym