Django HTML Minifier
django-htmlmin is an HTML minifier designed for Python web frameworks, primarily Django. It provides middleware and utility functions to reduce HTML size, improving page load times. The current version is 0.11.0, released in March 2019, and while functional, it is considered less actively maintained than some alternatives.
Warnings
- gotcha There is a separate, unrelated package named `htmlmin` on PyPI which is a standalone HTML minifier. Importing `htmlmin.minify.html_minify` from `django-htmlmin` will work, but be aware of the naming conflict if you attempt to use both libraries or refer to external `htmlmin` documentation.
- gotcha The order of middleware is critical. `MarkRequestMiddleware` should be placed after `FetchFromCacheMiddleware`, and `HtmlMinifyMiddleware` should be placed after `UpdateCacheMiddleware` if Django's caching middleware is used. Placing minification middleware incorrectly can lead to unminified output or errors.
- deprecated The `django-htmlmin` project has not seen updates since March 2019. While functional, it is not actively maintained, and faster, more actively developed alternatives exist (e.g., `django-minify-html`).
- gotcha By default, `django-htmlmin` only minifies HTML responses when Django's `DEBUG` setting is `False`. To enable minification during development (when `DEBUG` is `True`), you must explicitly set `HTML_MINIFY = True` in your Django settings.
Install
-
pip install django-htmlmin
Imports
- HtmlMinifyMiddleware
from htmlmin.middleware import HtmlMinifyMiddleware
- MarkRequestMiddleware
from htmlmin.middleware import MarkRequestMiddleware
- html_minify
from htmlmin.minify import html_minify
- minified_response
from htmlmin.decorators import minified_response
Quickstart
# settings.py
INSTALLED_APPS = [
# ...
'htmlmin',
# ...
]
MIDDLEWARE = [
# ... other middlewares (e.g., GZipMiddleware, UpdateCacheMiddleware)
'htmlmin.middleware.MarkRequestMiddleware',
'htmlmin.middleware.HtmlMinifyMiddleware',
# ... other middlewares (e.g., FetchFromCacheMiddleware, DebugToolbarMiddleware)
]
# Optional: Enable minification in DEBUG mode
# HTML_MINIFY = True
# Optional: Exclude specific URL patterns from minification
# EXCLUDE_FROM_MINIFYING = ('^/admin/', '^/api/')
# views.py example for decorator
from django.shortcuts import render
from htmlmin.decorators import minified_response
@minified_response
def my_minified_view(request):
return render(request, 'my_template.html', {'data': 'Some content'})