Search code examples
pythondjangodjango-staticfilesdjango-static

Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT


What are the differences of these three static url?

I am not sure if I am right, I am using the MEDIA_ROOT to store my uploaded photos (via models.ImageField())

However, I created a JS script to my admin and in admin.py. I defined the media as below:

....
class Media:
      js = ('/admin/custom.js', )

and my settings.py:

 ....
 STATIC_ROOT = "/home/user/project/django1/top/listing/static"

and I added the custom.js to STATIC_ROOT/admin/custom.js, but it is not working. Throwing 404 not found error.

And then I change the STATIC_ROOT to STATICFILES_DIRS, and it works!!

....
STATICFILES_DIRS = "/home/user/project/django1/top/listing/static"

So, I am not understand what is going on here. In fact, I just don't understand what is the difference between STATIC_ROOT and STATICFILES_DIRS.

Currently I am testing Django in my machine via virtualenv, not deployed yet, is it the reason STATIC_ROOT not working??


Solution

  • You can find these settings in the Django documentation. Here are my own definitions and quotations from the documentation:

    • MEDIA_ROOT is the folder where files uploaded using FileField will go.

      Absolute filesystem path to the directory that will hold user-uploaded files.

    • STATIC_ROOT is the folder where static files will be stored after using manage.py collectstatic

      The absolute path to the directory where collectstatic will collect static files for deployment.

      If the staticfiles contrib app is enabled (default) the collectstatic management command will collect static files into this directory. See the howto on managing static files for more details about usage.

    • STATICFILES_DIRS is the list of folders where Django will search for additional static files aside from the static folder of each app installed.

      This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view.

    In your settings, you should have:

    MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
    STATIC_ROOT = os.path.join(BASE_DIR, "static/")
    
    # Make a tuple of strings instead of a string
    STATICFILES_DIRS = ("/home/user/project/django1/top/listing/static", )
    

    ...where:

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    

    as defined in the default Django settings.py now.