Django – Static Files

Static Files is a Django app that helps with serving static content.

This tutorial is meant as a short and quick guide on how to configure your Django project to serve static based content.
To achieve this we will configure Django (via settings.py) and Apache. Our example will be based on serving static content from the folder ‘/opt/django/myproject/static/’.

settings.py

First of all the following settings are added to the settings of your Django project.

STATIC_ROOT = ‘/opt/django/myproject/static/’
STATIC_URL = ‘/static/’
ADMIN_MEDIA_PREFIX = ‘/static/admin/’

TEMPLATE_CONTEXT_PROCESSORS = (
    ‘django.core.context_processors.debug’,
    ‘django.core.context_processors.i18n’,
    ‘django.core.context_processors.media’,
    ‘django.core.context_processors.static’,
    ‘django.contrib.auth.context_processors.auth’,
    ‘django.contrib.messages.context_processors.messages’,
)

STATICFILES_FINDERS = (
    ‘django.contrib.staticfiles.finders.FileSystemFinder’,
    ‘django.contrib.staticfiles.finders.AppDirectoriesFinder’,
)

TEMPLATE_LOADERS = (
    ‘django.template.loaders.filesystem.Loader’,
    ‘django.template.loaders.app_directories.Loader’,
)

INSTALLED_APPS = (
    ‘django.contrib.auth’,
    ‘django.contrib.contenttypes’,
    ‘django.contrib.sessions’,
    ‘django.contrib.sites’,
    ‘django.contrib.messages’,
    ‘django.contrib.staticfiles’,
    ‘myproject’,
)

Apache Configuration

 Within the Apache configuration the Alias directive is defined.

<VirtualHost *:80>
        ServerName my.example.com
        WSGIScriptAlias / /opt/django/myproject/apache/django.wsgi
        Alias /static/ /opt/django/myproject/static/
</VirtualHost>

Collect Files

In order to copy all of your static content to your STATIC_ROOT the following command is used.

python manage.py collectstatic

Note : The urls that your static files are collected from are defined via the STATICFILES_DIRS setting (from within settings.py).

Note

If you have no requirement to collect your static files from the paths defined within STATICFILES_DIRS then,

  • STATIC_ROOT should not be defined (i.e STATIC_ROOT = ” )
  • STATICFILES_DIRS should be configured as the absolute path to your static files.

A good reference on this can be found here.

Rick Donato

Want to become a Django expert?

Here is our hand-picked selection of the best courses you can find online:
The Complete Web Development Bootcamp course
Django Practical Guide course
Django Full Stack Developer Bootcamp
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial