Django Compressor

4.6.0 · active · verified Sat Apr 11

Django Compressor is a reusable Django application that processes, combines, and minifies linked and inline JavaScript and CSS within Django templates into cacheable static files. It supports various compilers like CoffeeScript, LESS, and SASS, and offers extensibility for custom processing steps. As of version 4.6.0, it remains actively maintained with a regular release cadence, ensuring compatibility with recent Django versions.

Warnings

Install

Imports

Quickstart

To quickly integrate Django Compressor, add 'compressor' to `INSTALLED_APPS` and 'compressor.finders.CompressorFinder' to `STATICFILES_FINDERS`. Define `STATIC_URL` and `STATIC_ROOT`. Use the `{% load compress %}` and `{% compress css %}`/`{% compress js %}` template tags around your static and inline assets. For production, set `COMPRESS_ENABLED = True` and typically `COMPRESS_OFFLINE = True`, then run `python manage.py collectstatic` followed by `python manage.py compress` during deployment to pre-process assets.

import os

# settings.py example

DEBUG = True # Or False, affects compression behavior

INSTALLED_APPS = [
    # ... other apps
    'django.contrib.staticfiles',
    'compressor',
]

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'staticfiles')

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'compressor.finders.CompressorFinder',
)

# COMPRESS_ENABLED defaults to not DEBUG. Set explicitly for consistent behavior.
COMPRESS_ENABLED = not DEBUG # For production, typically True
COMPRESS_OFFLINE = True # For pre-compressing assets during deployment

# Example template (e.g., base.html)
# {% load static compress %}
#
# <head>
#     {% compress css %}
#         <link rel="stylesheet" href="{% static 'css/base.css' %}">
#         <style>body { font-family: sans-serif; }</style>
#     {% endcompress %}
# </head>
# <body>
#     <!-- Content -->
#     {% compress js %}
#         <script src="{% static 'js/main.js' %}"></script>
#         <script>console.log('Hello from inline JS!');</script>
#     {% endcompress %}
# </body>

# --- Steps to run ---
# 1. Add above settings to your project's settings.py.
# 2. Add the template code to one of your Django templates.
# 3. Create static/css/base.css and static/js/main.js in an app's static directory.
# 4. Run:
#    python manage.py collectstatic --noinput
#    python manage.py compress
# 5. Start development server:
#    python manage.py runserver
# 6. View the rendered page source; you should see compressed CSS/JS links.

view raw JSON →