Login

Dynamic import from an installed app

Author:
Archatas
Posted:
April 2, 2009
Language:
Python
Version:
1.0
Tags:
dynamic import
Score:
2 (after 2 ratings)

This is an example how to dynamically import modules other than models.py from installed apps. It allows you to define the full module path just once in INSTALLED_APPS in the settings.

Using this technique makes it possible to write extensible and reusable apps as mentioned in Abstract Models and Dynamicly Assigned Foreign Keys.

Probably, it would be great to have some helpers for doing this in django itself. For example:

from django.db import models
from django.utils import importlib

def import_installed(path):
    """
    Imports a module from an installed app

    >>> import_installed("myapp.forms")
    <module 'myproject.apps.myapp.forms'>
    """
    app_name, module = path.split(".", 1)
    app = models.get_app(app_name)
    return importlib.import_module(app.__name__[:-6] + module)

UPDATE: Reported as ticket #10703

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.db import models
from django.utils import importlib

# get the installed models.py from the installed app
app = models.get_app("myapp")

# import the views from the same app
views = importlib.import_module(app.__name__[:-6] + "views")

# import templatetags from the same app
mytemplatetags = importlib.import_module(app.__name__[:-6] + "templatetags.mytemplatetags")

# import any other module from the same app
myothermodule = importlib.import_module(app.__name__[:-6] + "myothermodule")

More like this

  1. Test runner that installs 'tests' packages as apps by adrian_lc 1 year, 7 months ago
  2. Dynamically change admin widgets at runtime by davisd 5 years ago
  3. Dynamic thumbnail generator by semente 7 years, 2 months ago
  4. Single Django App behind multiple Apache Proxies by chadmaine 7 years, 12 months ago
  5. TestSettingsManager: temporarily change settings for tests by carljm 6 years, 8 months ago

Comments

Please login first before commenting.