[Django]-Importance of apps orders in INSTALLED_APPS

37👍

Yes, the order is quite important.

From Django official docs on INSTALLED_APPS settings:

When several applications provide different versions of the same
resource (template, static file, management command, translation), the
application listed first in INSTALLED_APPS has precedence.

Example-1 Templates:

django.template.loaders.app_directories.Loader

If this template loader is enabled in your DjangoTemplates backend in the TEMPLATES setting or if you have passed it as a loaders argument to Engine, then it loads templates from Django apps on the filesystem.

For each app in INSTALLED_APPS, the loader looks for a templates subdirectory. If the directory exists, Django will look for templates in there.

Lets say in my project, i have defined INSTALLED_APPS as:

INSTALLED_APPS = ('myproject.app1', 'myproject.app2')

Now, i want to get the template some_template.html. Then get_template('some_template.html') will look for some_template.html in these directories, in this order:

/path/to/myproject/app1/templates/ # checks here first
/path/to/myproject/app2/templates/ # Then checks here

It will then use the one which it finds first.

Quoting from that section:

The order of INSTALLED_APPS is significant!

Example-2: Translations

Django applies the following algorithm for discovering translations:

  1. The directories listed in LOCALE_PATHS have the highest precedence, with the ones appearing first having higher precedence than the ones appearing later.
  2. Then, it looks for and uses if it exists a locale directory in each of the installed apps listed in INSTALLED_APPS. The ones appearing first have higher precedence than the ones appearing later.
  3. Finally, the Django-provided base translation in django/conf/locale is used as a fallback.

We can see that order is important here also.

Example-3 Management Commands:

From Django 1.7 release notes on management commands and order of INSTALLED_APPS:

When several applications provide management commands with the same
name, Django loads the command from the application that comes first
in INSTALLED_APPS. Previous versions loaded the command from the
application that came last.

This brings discovery of management commands in line with other parts
of Django that rely on the order of INSTALLED_APPS, such as static
files, templates, and translations.

3👍

I experimented a bit and found two other things that I deemed useful to know:

  1. The order in INSTALLED_APPS doesn’t seem to effect when the models are created. Django figures out that certain models depend on others and run them in the correct order.

  2. The apps ready method in the AppConfig object seems to run in the order they appear in INSTALLED_APPS.

Leave a comment