0
0
DjangoHow-ToBeginner · 3 min read

How to Configure Static Files in Django: Simple Setup Guide

To configure static files in Django, set STATIC_URL to define the URL prefix for static files, use STATICFILES_DIRS to list folders with static files during development, and set STATIC_ROOT to specify the folder where static files are collected for production. Then run python manage.py collectstatic to gather all static files in one place.
📐

Syntax

In your Django settings.py, configure these settings:

  • STATIC_URL: URL prefix for static files (e.g., '/static/').
  • STATICFILES_DIRS: List of folders where Django looks for static files during development.
  • STATIC_ROOT: Folder where static files are collected for production deployment.
python
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    BASE_DIR / 'static',
]

STATIC_ROOT = BASE_DIR / 'staticfiles'
💻

Example

This example shows a basic Django settings.py setup for static files and how to collect them for production.

python
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    BASE_DIR / 'static',
]

STATIC_ROOT = BASE_DIR / 'staticfiles'

# After setting these, run:
# python manage.py collectstatic

# This command copies all static files from apps and STATICFILES_DIRS into STATIC_ROOT.
Output
Collecting static files... Copying static/css/style.css Copying static/js/app.js ... Static files copied to staticfiles directory.
⚠️

Common Pitfalls

Common mistakes include:

  • Not setting STATIC_ROOT before running collectstatic, causing files not to be collected.
  • Forgetting to add static folders to STATICFILES_DIRS during development, so files don’t load.
  • Using STATIC_URL without trailing slash, which can break URLs.
  • Not configuring your web server (e.g., Nginx) to serve files from STATIC_ROOT in production.
python
## Wrong (missing STATIC_ROOT)
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']

# Running collectstatic will fail or do nothing.

## Right
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'
📊

Quick Reference

SettingPurposeExample Value
STATIC_URLURL prefix for static files'/static/'
STATICFILES_DIRSFolders with static files during development[BASE_DIR / 'static']
STATIC_ROOTFolder to collect static files for productionBASE_DIR / 'staticfiles'
collectstaticCommand to gather static filespython manage.py collectstatic

Key Takeaways

Always set STATIC_URL with a trailing slash to define static file URLs.
Use STATICFILES_DIRS to tell Django where to find static files during development.
Set STATIC_ROOT before running collectstatic to gather files for production.
Run python manage.py collectstatic to prepare static files for deployment.
Configure your web server to serve files from STATIC_ROOT in production.