Coming from an Apache / php world there is something i can’t figure out searching for django Development best practices :
With symfony2 framework (or even java Play!) you always have a “public” folder and the webserver only serve files from this folder. Obvious Strategy for security reason it is also clear during dev process to put public files in this folder.
In django it is not clear at all : from my readings it appears as good practice to have a static folder at root level PLUS a Media folder for UGC files and à template folder. No main “public” folder.
Can someone help me to clear my mind here ? Would’t it be more secure to have one folder to contain all requests and protect the rest of the app ?
Tanks
There are two different types of ‘static’ files in django.
Since these are two different categories of static files, django offers two mechanisms to deal with them. As the first is more common than the second (you may not have an application that requires users to upload files), dealing with the first condition comes built in with django.
As per the standard layout, applications that require static files will include them in a directory called
staticwithin the application directory. Django will search for this directory inside any app that is inINSTALLED_APPSfor static files. If you have files that are not tied to any app, you can put them in a separate directory. This directory should be added toSTATICFILES_DIRS(a tuple) so django is aware of it.Once you have done this, the
collectstaticcommand will gather all the static files (from thestaticsubdirectories in all applications inINSTALLED_APPSand any directory inSTATICFILES_DIRS) and put them in a directory pointed to bySTATIC_ROOT; this is so{{ STATIC_URL }}tags work correctly in templates.Now, all you do is move/point/link the
STATIC_ROOTdirectory so that its accesible from the web. Django expects that all files inSTATIC_ROOTare accessible at the root URL that specified bySTATIC_URL.For user uploaded files, django is more hands off. All it really cares about is that you don’t put your user uploaded files in the same place as the
collectstaticcommand will be using to read its files – this means, that theMEDIA_ROOTcannot be a directory or subdirectory ofSTATICFILE_DIRS(if you have specified any directories here, typically this setting is undefined in vanilla django setups).MEDIA_ROOTis a directory that django can manipulate by creating subdirectories under the root (see theFileFielddocumentation for example).MEDIA_URLis the URL prefix that points to the root for user-uploaded files. This is so that commands that generate automatic URLs for models work correctly.As these are two different classes of static files, there are two different types of security and deployment requirements. For example, you might want to store user uploaded files in a S3 bucket but put your application’s assets somewhere else.
This is why these two similar things are segregated in django.