For example I have 2 apps in my django project with templates and static files with identical subpath:
app1 /
static /
style.css
templates /
index.html
app2 /
static /
style.css
templates /
index.html
than, in settings.py I added this two apps:
INSTALLED_APPS = (
'app1',
'app2',
)
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?
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.
https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#django-admin-collectstatic
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With