Django Static Files Handling

Static files in Django refer to files like CSS, JavaScript, images, and fonts that are served to the client as-is. Django provides a powerful framework for managing and serving these files during both development and production.

How Static Files Work in Django

1. Static Files in Development:

Django’s built-in development server automatically serves static files without requiring additional configuration.

Files are located in the STATICFILES_DIRS directory or app-specific static/ directories.

2. Static Files in Production:

Static files are collected into a single directory using the collectstatic command.


python manage.py collectstatic

These files are served by a web server like Nginx or Apache.

How to Configure Static Files?

1. Directory Structure

The typical structure for static files in a Django project:


myproject/
    ├── myapp/
    │   ├── static/
    │   │   └── myapp/
    │   │       ├── css/
    │   │       │   └── styles.css
    │   │       ├── js/
    │   │       │   └── script.js
    │   │       └── images/
    │   │           └── logo.png
    ├── static/
    │   └── global/
    │       └── css/
    │           └── global_styles.css
    ├── settings.py

2. Settings

In your settings.py, configure the static files:


# settings.py

# URL for accessing static files
STATIC_URL = '/static/'

# Directories for collecting static files (development)
STATICFILES_DIRS = [
    BASE_DIR / "static",  # Your global static files
]

# Directory where collected static files are stored (production)
STATIC_ROOT = BASE_DIR / "staticfiles"

Adding Static Files to Templates

To use static files in templates, load the static template tag and reference the files.


{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'global/css/global_styles.css' %}">
    <title>Static Files Example</title>
</head>
<body>
    <h1>Welcome to Django Static Files</h1>
    <img src="{% static 'myapp/images/logo.png' %}" alt="Logo">
    <script src="{% static 'myapp/js/script.js' %}"></script>
</body>
</html>