Preparing Static Assets
Learn about Preparing Static Assets
Understanding Static Files in Django
Static files are assets like CSS stylesheets, JavaScript files, images, and fonts that do not change based on user input. Django has a built-in static files framework that collects all static assets from your apps and project directories into a single location for production serving.
Organizing Static Files
Create a static directory inside your contacts app. Inside it, create subdirectories for css, js, and images. Place any custom stylesheets or scripts in the appropriate folders. Reference these files in your templates using the static template tag.
Configuring Static Settings
In settings.py, verify that STATIC_URL is set to "/static/". Add a STATIC_ROOT setting that points to a directory like BASE_DIR / "staticfiles". This is where Django will collect all static files when you run the collectstatic command.
Running collectstatic
Before deploying, run the collectstatic management command:
python manage.py collectstatic
This copies all static files from every app and from STATICFILES_DIRS into the STATIC_ROOT directory.
Using WhiteNoise
For platforms like Render or Heroku, install WhiteNoise to serve static files efficiently without needing a separate web server like Nginx:
pip install whitenoise
Add WhiteNoise's middleware to your MIDDLEWARE list, right after SecurityMiddleware. WhiteNoise compresses and caches your static files automatically for optimal performance.
Freezing Requirements
Generate a requirements.txt file that lists all your Python dependencies and their exact versions:
pip freeze > requirements.txt