Login

Dynamic import from an installed app

Author:
Archatas
Posted:
April 2, 2009
Language:
Python
Version:
1.0
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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 3 weeks ago
  2. Python Django CRUD Example Tutorial by tuts_station 1 month, 1 week ago
  3. Browser-native date input field by kytta 2 months, 3 weeks ago
  4. Generate and render HTML Table by LLyaudet 3 months ago
  5. My firs Snippets by GutemaG 3 months ago

Comments

Please login first before commenting.