Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organizing templates in a django project

I am trying to use the "app-specific" approach to organizing various django apps. For example:

- app2
    - __init__.py
    - urls.py
    - views.py
    - templates/
- app2
    - __init__.py
    - urls.py
    - views.py
    - templates/
- manage.py
- settings.py
- urls.py

One issue I'm having with this though is where to put the base templates that everything inherits from? For example, at the top of all my templates I have {% includes "base.html" %}, but if I'm doing the above I don't see how I could do this in a logical fashion.

like image 992
David542 Avatar asked Oct 20 '25 18:10

David542


2 Answers

First thing first, You want "templates/appXXX/" for per-app templates (at least if you want to use "appXXX/template.html").

Second point: as you just found out, not all templates (and not all code FWIW) are strictly related to one given app. At one point you need to integrate your apps together to build a full website / webapp, and templates - specially the base template - are part of the project's "integration" layer. IOW: just create a templates directory in your project's root and put your base template there. That's what everyone expects anyway...

like image 170
bruno desthuilliers Avatar answered Oct 23 '25 06:10

bruno desthuilliers


This kind of question is sometimes closed as primarily-opinion-base; I'll give my two cents anyways, because I think it is a valid question.

The structure I use is the following (successfully employed in some Django projects that have less than 10 apps inside each project):

In the first image you can see that for this project I started every app name with the prefix app_, but that is just an internal convention. Note: the folder .venv contains the Python virtual environment, and that folder is not version controlled (the other folders are part of the git repo).

enter image description here

In the second image you can see that I have a folder project_config that contains settings, base urls, middleware, routers and other stuff. Note: Django docs usually name this folder the same as the project (which would be tb_system_01 in this case), but I find the name project_config more meaningful for my use cases).

Then I usually use folders project_config/static and project_config/templates to store all the stuff that is common to the apps. Here also go my base templates, which would be my answer to the specific question you asked. The Django docs sometimes suggest using a top-level folder called templates, but for my use cases I found it more organized to have that folder inside of project_config/.

enter image description here

like image 43
Ralf Avatar answered Oct 23 '25 07:10

Ralf



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!