Difference between static STATIC_URL and STATIC_ROOT on Django

user993563 picture user993563 · Dec 31, 2011 · Viewed 107.5k times · Source

I am confused by static root and want to clarify things.

To serve static files in Django, the following should be in settings.py and urls.py:

import os
PROJECT_DIR=os.path.dirname(__file__)

1. Absolute path to the directory in which static files should be collected

STATIC_ROOT= os.path.join(PROJECT_DIR,'static_media/')

2. URL prefix for static files

STATIC_URL = '/static/'

3. Additional locations for static files

STATICFILES_DIRS = ( os.path.join(PROJECT_DIR,'static/'),)

...and in urls.py the following lines:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += patterns('', (
    r'^static/(?P<path>.*)$',
    'django.views.static.serve',
    {'document_root': settings.STATIC_ROOT}
))

4. We also use python manage.py collectstatic

Questions:

  1. Could anyone please explain the workflow to me: how should things ideally be done. As of now, I copy/paste the above code snippets into their designated locations and continue making new files in the static directory and it works. In my settings.STATIC_ROOT, however, I have pointed to a different directory.

  2. It would be great if someone could explain the workflow of each setting: how files are collected and managed, and what would be a good practice to follow.

Thanks.

Answer

suhailvs picture suhailvs · Sep 5, 2013

STATIC_ROOT

The absolute path to the directory where ./manage.py collectstatic will collect static files for deployment. Example: STATIC_ROOT="/var/www/example.com/static/"

now the command ./manage.py collectstatic will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/. now you only need to serve this directory on apache or nginx..etc.

STATIC_URL

The URL of which the static files in STATIC_ROOT directory are served(by Apache or nginx..etc). Example: /static/ or http://static.example.com/

If you set STATIC_URL = 'http://static.example.com/', then you must serve the STATIC_ROOT folder (ie "/var/www/example.com/static/") by apache or nginx at url 'http://static.example.com/'(so that you can refer the static file '/var/www/example.com/static/jquery.js' with 'http://static.example.com/jquery.js')

Now in your django-templates, you can refer it by:

{% load static %}
<script src="{% static "jquery.js" %}"></script>

which will render:

<script src="http://static.example.com/jquery.js"></script>