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
- Serializer factory with Django Rest Framework by julio 3 months, 3 weeks ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 4 months, 1 week ago
- Help text hyperlinks by sa2812 5 months ago
- Stuff by NixonDash 7 months, 1 week ago
- Add custom fields to the built-in Group model by jmoppel 9 months, 2 weeks ago