There are two different types of 'static' files in django.
- Bundled resources/assets with applications (css,javascript typically)
- Any files uploaded by your users.
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 static
within the application directory. Django will search for this directory inside any app that is in INSTALLED_APPS
for 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 to STATICFILES_DIRS
(a tuple) so django is aware of it.
Once you have done this, the collectstatic
command will gather all the static files (from the static
subdirectories in all applications in INSTALLED_APPS
and any directory in STATICFILES_DIRS
) and put them in a directory pointed to by STATIC_ROOT
; this is so {{ STATIC_URL }}
tags work correctly in templates.
Now, all you do is move/point/link the STATIC_ROOT
directory so that its accesible from the web. Django expects that all files in STATIC_ROOT
are accessible at the root URL that specified by STATIC_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 collectstatic
command will be using to read its files - this means, that the MEDIA_ROOT
cannot be a directory or subdirectory of STATICFILE_DIRS
(if you have specified any directories here, typically this setting is undefined in vanilla django setups).
MEDIA_ROOT
is a directory that django can manipulate by creating subdirectories under the root (see the FileField
documentation for example).
MEDIA_URL
is 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.