Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for the nested template directory structure in Django?

Tags:

python

django

The django template folder requires creating a subfolder with the name of the app which then contains the template files. Why is this necessary, when python manage.py collectstatic can infer this information while traversing all directories? It seems very redundant.

like image 868
2080 Avatar asked Oct 27 '25 21:10

2080


1 Answers

First of all, Django does not require this specific folder structure for templates to work, it is just a stablished pattern to do so. And, of course, it has a rationale, as pointed in the official doc:

Template namespacing

Now we might be able to get away with putting our templates directly in polls/templates (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.

You can reference to this question or that another for concrete cases.

In a nutshell, by following this pattern you can have your templates organized in 2 groups:

  1. templates related to your specific site or project can live inside the directory pointed by the TEMPLATES['DIRS'] setting;
  2. templates related to a specific app, that could be served as is if you make your app pluggable, should live inside './appname/templates/appname/' (and TEMPLATES['APP_DIRS'] must be True). This way you avoid name conflicts between files inside this folder anf files from outside.
like image 137
Rodrigo Rodrigues Avatar answered Oct 29 '25 11:10

Rodrigo Rodrigues



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!