← Back to Chapters

Managing STATIC_URL & STATICFILES_DIRS

?️ Managing STATIC_URL & STATICFILES_DIRS

? Quick Overview

Static files such as CSS, JavaScript, and images are essential for Django applications. Django provides built-in settings like STATIC_URL and STATICFILES_DIRS to manage these assets efficiently in development and production.

? Key Concepts

  • Static files do not change dynamically
  • Django collects and serves static assets differently in dev and prod
  • Settings control how and where files are accessed

? What are Static Files?

Static files include CSS, JavaScript, images, fonts, and other assets required for frontend rendering. Django uses its staticfiles framework to manage them.

⚙️ What is STATIC_URL?

STATIC_URL defines the public URL path for static files.

? View Code Example
# URL prefix for static files
STATIC_URL = '/static/'

⚙️ What is STATICFILES_DIRS?

This setting tells Django where to look for additional static files.

? View Code Example
# Additional directories for static files
STATICFILES_DIRS = [
BASE_DIR / "static",
]

? Using Static Files in Templates

? View Code Example
# Load static template tag
{% load static %}
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<img src="{% static 'images/logo.png' %}" alt="Logo">

? Serving Static Files in Development

? View Code Example
# Enable staticfiles app
INSTALLED_APPS = [
'django.contrib.staticfiles',
]

?️ Serving Static Files in Production

? View Code Example
# Collect static files
python manage.py collectstatic

?️ Simulator: How Django Resolves URLs

Change the settings below to see how Django translates settings and template tags into actual HTML.

1. settings.py Configuration

STATIC_URL = '/static/'

2. Template Syntax

{% static 'css/main.css' %}

3. Final Rendered HTML

<link href="/static/css/main.css">

✅ Tips & Best Practices

  • Always run collectstatic before deployment
  • Organize assets into folders like css/, js/, images/
  • Use a web server (Nginx/Apache) in production

? Try It Yourself

  • Create a static folder and add your own CSS
  • Modify STATICFILES_DIRS and test asset loading
  • Run collectstatic and inspect output directory