Getting started with static files in Django

For the first time I worked with Django (v1.1), I had to do something like: adding the url pattern point to static directory of my project in the main urls.py file:

...
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': False}),
...


In the newest version of Django (1.5.1) which I'm using right now, all I have to do is:

1. Put  the static files in a static subdirectory of my apps (myapp/static/) or list absolute path to static directories in

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    #~ '/home/projects/mystatics/',
)

Django will serves your app static files by looking for them in those above directories. 

2. Leave the main static directory (the STATIC_ROOT) blank.

3. Run the command line: ./manage.py collectstatic

This will copy all the static files from static subdirectory of your apps and from directories you listed in STATICFILES_DIRS setting.

This is used in production servers. You point to it in nginx configuration.

4. And in the templates, use {{ STATIC_URL }} to point to the static file, e.g.:

<script src="{{ STATIC_URL }}js/jquery.min.js"></script> 


Note: in development environment, {{ STATIC_URL }} is the path to your app's static (myapp/static), not your main static directory (myproject/static, the STATIC_ROOT)

I recommend you to read the tutorial at http://agiliq.com/blog/2013/03/serving-static-files-in-django/ for deeper understanding if the Django's documentation is too much for you...and me :D.


Just cool!

Comments