Django - Using WhiteNoise with Django

Aug 3, 2017 Djnago 中文版

In this post, I’m going to show you how to use WhiteNoise to serve static resources for your Django application. But, you might think why I need another software to do that? In development envrionment (debug mode), Django provides a default mechanism to help you on serving static files. However, the Django team strongly suggests you should have different ways to serve them in production, such as using Nginx, Apache or AWS S3. Thus, WhiteNoise would be a good and simple choice if your Django application is a MVP or a low-traffic website.



Prerequisite

If you have not created a proper environment for the following steps, you can use below commands:

# Install Django
python -m pip install Django

# Check Django's version
python -m django --version

# Create a new Django project
django-admin startproject <project-name>

The structure of your project should look like this:

project-name/
├── project-name
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py


Install WhiteNoise

To install WhiteNoise, pip would be the easiest way:

python -m pip install whitenoise


Integrate WhiteNoise with Django

There are not too much things to do in this step. All we need is to add the following settings into your settings.py:

# Add WhiteNoise into middlewares
MIDDLEWARE = [
    ...
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

# Choose a folder to put all apps' static files
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Of course, you can find more options from here.

Collect static files

Since we’ve decided a place for gathering all apps’ static resources, we need to copy and put them to that place by executing the command:

python manage.py collectstatic --noinput

After copying and moving, WhiteNoise will automatically serve static files when the Django is up. Don’t forget Django will take over that task when the debug mode is on.


You might also like:




If you have any suggestions, questions or even find some typos, feel free to contact me. Thank you! :)

zeckli.devforgalaxy@gmail.com   © 2015-2019 zeckli, thanks to Jekyll and GitHub.