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__)
STATIC_ROOT= os.path.join(PROJECT_DIR,'static_media/')
STATIC_URL = '/static/'
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}
))
python manage.py collectstatic
Questions:
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.
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.
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.
The
URL
of which the static files inSTATIC_ROOT
directory are served(by Apache or nginx..etc). Example:/static/
orhttp://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>