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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.