Static and Media Settings

A snippet showing how to configure static and media file paths.


# settings.py

from pathlib import Path
import os

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

# Static files (CSS, JavaScript, Images)
STATIC_URL = "/static/"
STATICFILES_DIRS = [BASE_DIR / "static"]  # local dev assets
STATIC_ROOT = BASE_DIR / "staticfiles"    # collected for deployment

# Media files (uploads)
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"
      

# Collect static files before deployment
python manage.py collectstatic

# Example directory layout after collectstatic:
# ├── project/
# │   ├── static/        # development assets
# │   ├── staticfiles/   # deployment-ready, collected files
# │   └── media/         # user uploads
      

# way to access static and media files:
- Access static files via /static/ (e.g., /static/css/style.css).
- Access user uploads via /media/ (e.g., /media/profile.jpg).
- In production, serve STATIC_ROOT and MEDIA_ROOT via web server (Nginx, Apache, S3, etc.).
      
Explanation:
  • STATICFILES_DIRS holds dev-only assets; STATIC_ROOT is for deployment (collected).
  • Run collectstatic before deploying so all static files live in one place.
  • Store user-uploaded content in MEDIA_ROOT and access it via MEDIA_URL.
  • In production, serve static/media files using a web server or cloud storage for performance.
  • Category Deployment & Settings
  • Total Views 908
  • Last Modified 20 November, 2025
  • Tags #settings #static #media #files
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.