Django - Collect Static Files
Handle Static Files
Static files in your project, like stylesheets, JavaScripts, and images,are not handled automatically by Django whenDEBUG = False.
WhenDEBUG = True, this worked fine, all we had to do was to put them in thestatic folder of the application.
WhenDEBUG = False, static files have to be collectedand put in a specified folder before we can use it.
Collect Static Files
To collect all necessary static files for your project, start by specifying aSTATIC_ROOT property in thesettings.py file.
This specifies a folder where you want to collect your static files.
You can call the folder whatever you like, we will call itproductionfiles:
my_tennis_club/my_tennis_club/settings.py:
..STATIC_ROOT = BASE_DIR / 'productionfiles'STATIC_URL = 'static/'..You could manually create this folder and collect and put all static files of your projectinto this folder, but Django has a command that do this for you:
Which will produce this result:
128 files? Why so many? Well this is because of the admin user interface, that comes built-in with Django.We want to keep this feature in production, and it comes with a whole bunch of files including stylesheets, fonts, images, and JavaScripts.
If you check in the filesystem on your computer, you will see that a new folder was created:productionfiles.This folder containsadmin, with the static files for the admin UI,and themyfirst.css file you created in theAdd Static Files chapter.
members/
my_tennis_club/
productionfiles/
admin/
myfirst.css
The Example Should Work
Now you have collected the static files of your project, and if you haveinstalled WhiteNoise, the example from theAdd Static Files chapter will finally work.
Start the server and see the result:
And check out the result in your own browser:127.0.0.1:8000/testing/.
Example
my_tennis_club/members/templates/template.html:
{% load static %}<!DOCTYPE html><html><link rel="stylesheet" href="{% static 'myfirst.css' %}"><body>{% for x in fruits %} <h1>{{ x }}</h1>{% endfor %}</body></html>Run Example »
