How to Use collectstatic in Django: Syntax and Examples
Use the
python manage.py collectstatic command to gather all static files from your apps and static folders into the directory specified by STATIC_ROOT. This prepares your static files for production by centralizing them in one place.Syntax
The basic syntax to collect static files in Django is:
python manage.py collectstatic: Runs the command to collect all static files.--noinput: Optional flag to run without asking for confirmation.--clear: Optional flag to clear the target directory before collecting.
The command uses the STATIC_ROOT setting to know where to copy the files.
bash
python manage.py collectstatic [--noinput] [--clear]
Example
This example shows how to set up STATIC_ROOT in settings.py and run collectstatic to gather static files into that folder.
python
# settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Then run in terminal: # python manage.py collectstatic --noinput
Output
Copying static files to /path/to/project/staticfiles
127 static files copied.
Common Pitfalls
Common mistakes when using collectstatic include:
- Not setting
STATIC_ROOTinsettings.py, so files have nowhere to collect. - Running
collectstaticwithout clearing old files, causing stale files to remain. - Forgetting to run
collectstaticafter adding or changing static files. - Running
collectstaticin development without needing it, since Django serves static files automatically in debug mode.
python
Wrong: # settings.py STATIC_URL = '/static/' # STATIC_ROOT not set Right: # settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Quick Reference
Tips for using collectstatic effectively:
- Always set
STATIC_ROOTto an absolute path for production. - Use
--noinputflag for automated deployments. - Run
collectstaticafter any static file changes before deploying. - Use
--clearto remove old files if needed.
Key Takeaways
Set STATIC_ROOT in settings.py to specify where static files collectstatic copies files.
Run python manage.py collectstatic to gather all static files into STATIC_ROOT for production.
Use --noinput to avoid confirmation prompts during automated deployments.
Remember to run collectstatic after changing static files before deploying.
Avoid running collectstatic unnecessarily in development mode.