Saturday 31 August 2013

Serving Static Files in Django

This post shows the steps for setting up static files in Django.   Static files are things like images, logo's etc that won't change.  They are held within your Django project tree and then copied to a static files folder held outside your project tree, normally within the web server root.  The copy is kicked off by the collectstatic command shown below.

1. Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.


2. Settings.py:

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = 'C:/inetpub/wwwroot/static/'

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
  os.path.join(SITE_ROOT, 'static/'),
)
#STATICFILES_DIRS = (

3. Template:

    <img style= "width: 306px; height: 79px;" alt="my logo" src="{{ STATIC_URL }}logo.png" >

4.  Run python manage.py collectstatic to copy the static files into the STATICFILES_DIRS.

5.  In main urls.py:

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

6. For debug mode only add the following url to the urls.py file for the app (storing the static file folder):

if settings.DEBUG:
    urlpatterns += patterns( 'django.contrib.staticfiles.views' ,
        url(r '^static/(?P<path>.*)$', 'serve' ),
    )

No comments:

Post a Comment