Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Order of finding static files and templates in django-apps



For example I have 2 apps in my django project with templates and static files with identical subpath:

app1 / 
    static /
    templates /
app2 / 
    static /
    templates /

than, in settings.py I added this two apps:


now I use in some way 'style.css' and 'index.html' in templates, e.g.

{% include 'index.html' %}

so, question is:

Does Django guarantee that when I reference to 'style.css' or 'index.html' will be used files from app2 subdirectories?

Is it any other way to point Django preferable variants of files in such situation?

like image 875
Aleksey Avatar asked Feb 15 '23 04:02


1 Answers

As per documentation, first match wins:

Duplicate file names are by default resolved in a similar way to how template resolution works: the file that is first found in one of the specified locations will be used.


Now, when you tell Django to collect static files or render templates, Django asks special "finders" in order they are defined in your configuraiton for specified resource.

Default order for static files is "FileSystemFinder" that searches STATICFILES_DIRS in order they are added in it. If FileSystemFinder fails to find file in those dirs, Django uses next finder set, the "AppDirectoriesFinder" that searches in "static" subdirectories in your apps directories.

Same mechanic is applied to templates. When you tell Django to render "index.html", it first asks "filesystem.Loader" find template named like that in directories defined in TEMPLATE_DIRS. If search fails, Django asks next template loader, "app_directories.Loader" that searches template dirs in applications "templates" subdirs.

To answer your question, because app1 is registered before app2, Django will use it's style.css and index.html instead of ones coming from app2. If you want to change this behaviour, put app2 above app1 in your installed apps setting.

Documentation: https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.app_directories.Loader

like image 146
Ralfp Avatar answered Feb 17 '23 19:02