Django

Code

Auto All-Apps Module

For some larger django sites which use multiple django packages (Django Utils, Django Stuff and Django CMS Project) each containing multiple apps, it can get rather complex weaving the pieces into a whole.

It would be nice to have a single module with all the installed apps under it for easy access.

Here is the apps/_ _init_ _.py for such an auto-generated package:
(the package name 'apps' is just an example, could be anything)

def _init_apps():
    """import each of the installed apps into the module with the app name.
    writen as a function to keep the namespace clean
    """
    from django.conf import settings
    from warnings import warn
    gd = globals()
    for app in settings.INSTALLED_APPS:
        mod = __import__(app, '', '', [''])
        name = mod.__name__.split('.')[-1]
        if name in gd:
            if settings.DEBUG:
                warn('An app with the name "%s" (%s) has already been loaded and will shadow "%s"' % (
                    name, gd[name].__name__ , mod.__name__))
        else:
            gd[name] = mod

_init_apps()

Lets assume the fillowing is in your settings file:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'myproj.myapp',
    'stuff.tags',
    'gallery.apps.picturefolder',
    'cms.workflow.userprofile',
    'cms.workflow.cmsadmin',
    )

you could access these modules as follows:

from apps.auth.models import User
from apps.auth.forms import PasswordChangeForm
from apps.tags.models import Tag
from apps.userprofile.models import UserProfile
from apps.myapp.models import MyModel
from apps.cmsadmin.views import reset_password