I am planning a new Django project and want to get everything right and stuff. I stumbled over the question of how to organize the project directory layout. Luckily, there are quite a few examples of good project templates out there in the web. Still, there is one thing I struggle to get in my head:
It is the recommended way to put template files into a separate directory under the project root that is divided into subdirectories by apps. So, templates are not located within the app directories. That seems logical to me since we want to separate application logic from representation logic. But what about static files? Here, the common practice seems to be to locate the static files within the app dirs and load them into a ‘static’ directory under the project root at development time (collectstatic). And this logic I do not understand. Since static files (i.e. js, css, images) are usually accessed within templates, not within application code, I would count them to presentation logic. Then why aren’t they stored just like templates are – a directory under the project root, with subdirectories for the single apps?
I know I can store these files wherever I want but I guess there might be a good reason why folks are doing it this way. What could this reason be?
Static files can be put in the related app in the same way that templates related to a specific app are often put in the application directory.
Sometimes, it makes sense. Sometimes, it doesn’t – it’s your call.
For example, I put my static media in a
site_mediadirectory (global css, global images, etc) but put app specific media inapp/static. For example, if I have aPollapp, there’s a good chance that my media is only needed for the Poll app templates, and not my site index.The same goes for templates: I put my global templates (base.html) in a global template directory, but app specific templates go in
myapp/templates/myapp/foo.html.Finally, it particularly makes sense for pluggable apps. For example, django’s static files are stored in the app but becomes accessible in your static files directory even though the app lives somewhere on your python path. Previously, you would have had to copy the media directory or symlink to it.
The staticfiles app really shines because it lets you organize all files related to an application in one place: the application folder.
collectstatictakes care of the rest, and makes it all available at one location for a web server.