Use minify-html, the extremely fast HTML + JS + CSS minifier, with Django.

Overview

django-minify-html

https://img.shields.io/github/workflow/status/adamchainz/django-minify-html/CI/main?style=for-the-badge https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge https://img.shields.io/pypi/v/django-minify-html.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit

Use minify-html, the extremely fast HTML + JS + CSS minifier, with Django.

Requirements

Python 3.8 to 3.10 supported.

Django 2.2 to 4.0 supported.


Are your tests slow? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.


Installation

  1. Install with pip:

    python -m pip install django-minify-html
  2. Add django-minify-html to your INSTALLED_APPS:

    INSTALLED_APPS = [
        ...,
        "django_minify_html",
        ...,
    ]
  3. Add the middleware:

    MIDDLEWARE = [
        ...,
        "django_minify_html.middleware.MinifyHtmlMiddleware",
        ...,
    ]

    The middleware should be below any other middleware that may encode your responses, such as Django’s GZipMiddleware. It should be above any that may modify your HTML, such as those of django-debug-toolbar or django-browser-reload.

Reference

For information about what minify-html does, refer to its documentation.

django_minify_html.middleware.MinifyHtmlMiddleware

The middleware runs minify_html.minify() on the content of HTML responses. This function minifies HTML, and any inline JavaScript and CSS.

The middleware passes keyword arguments to minify() from its minify_args attribute, a dictionary of names to values. These correspond to the values in the Rust library’s Cfg structure, which have defaults in the Python library as visible in the source. By default the middleware overrides minify_css and minify_js to True. If you need to change an argument, subclass the middleware, replace minify_args, and use your subclass. For example, to preserve comments after minification:

from django_minify_html.middleware import MinifyHtmlMiddleware


class ProjectMinifyHtmlMiddleware:
    minify_args = MinifyHtmlMiddleware.minify_args | {
        "keep_comments": True,
    }

(This example uses Python 3.9’s dictionary merge operator.)

The middleware applies to all non-streaming, non-encoded HTML responses. To restrict this logic, you can subclass, override the should_minify() method, and use your subclass. The should_minify() method accepts the request and response, and returns a bool. For example, to avoid minification of URL’s with the URL prefix /admin/:

from django.http import HttpRequest, HttpResponse

from django_minify_html.middleware import MinifyHtmlMiddleware


class ProjectMinifyHtmlMiddleware:
    def should_minify(self, request: HttpRequest, response: HttpResponse) -> bool:
        return super().should_minify(request, response) and not request.path.startswith(
            "/admin/"
        )

Note that responses are minified even when DEBUG is True. This is recommended because HTML minification can reveal bugs in your templates, so it’s best to always work with your HTML as it will appear in production. Minified HTML is hard to read with “View Source” - it’s best to rely on the inspector in your browser’s developer tools.

Motivation

HTML minification is an underappreciated techinque for web optimization. It can yield significant savings, even on top of other tools like compression with Brotli or Gzip.

There is an existing package for HTML minification in Django, django-htmlmin. But it is much slower, since it does the minification in Python. At time of writing, it is also unmaintained, with no release since March 2019.

There are other minifiers out there, but in benchmarks minify-html surpasses them all. It’s a really well optimized and tested Rust library, and seems to be the best available HTML minifier.

Some CDN’s provide automatic minification, such as CloudFlare. This can be convenient, since it requires no application changes. But it adds some overhead: non-minified HTML has to first be transferred to the CDN, and the CDN has to parse the response, and recombine it. It also means that you don’t get to see the potential side effects of minification until your code is live. Overall it should be faster and more predictable to minify within Django, at the point of HTML generation.

Owner
Adam Johnson
🦄 @django technical board member 🇬🇧 @djangolondon co-organizer ✍ AWS/Django/Python Author and Consultant
Adam Johnson
Django + NextJS + Tailwind Boilerplate

django + NextJS + Tailwind Boilerplate About A Django project boilerplate/templa

Shayan Debroy 3 Mar 11, 2022
Dashboad Full Stack utilizando o Django.

Dashboard FullStack completa Projeto finalizado | Informações Cadastro de cliente Menu interatico mostrando quantidade de pessoas bloqueadas, liberada

Lucas Silva 1 Dec 15, 2021
A blog app powered by python-django

Django_BlogApp This is a blog app powered by python-django Features Add and delete blog post View someone else blog Can add comment to that blog And o

Manish Jalui 1 Sep 12, 2022
💨 Fast, Async-ready, Openapi, type hints based framework for building APIs

Fast to learn, fast to code, fast to run Django Ninja - Fast Django REST Framework Django Ninja is a web framework for building APIs with Django and P

Vitaliy Kucheryaviy 3.8k Jan 01, 2023
A Blog Management System Built with django

Blog Management System Backend use: Django Features Enhanced Ui

Vishal Goswami 1 Dec 06, 2021
Opinionated boilerplate for starting a Django project together with React front-end library and TailwindCSS CSS framework.

Opinionated boilerplate for starting a Django project together with React front-end library and TailwindCSS CSS framework.

João Vítor Carli 10 Jan 08, 2023
Strawberry-django-plus - Enhanced Strawberry GraphQL integration with Django

strawberry-django-plus Enhanced Strawberry integration with Django. Built on top

BLB Ventures 138 Dec 28, 2022
A helper for organizing Django project settings by relying on well established programming patterns.

django-configurations django-configurations eases Django project configuration by relying on the composability of Python classes. It extends the notio

Jazzband 953 Dec 29, 2022
Django based webapp pulling in crypto news and price data via api

Deploy Django in Production FTA project implementing containerization of Django Web Framework into Docker to be placed into Azure Container Services a

0 Sep 21, 2022
Developer-friendly asynchrony for Django

Django Channels Channels augments Django to bring WebSocket, long-poll HTTP, task offloading and other async support to your code, using familiar Djan

Django 5.5k Dec 29, 2022
A Django app to initialize Sentry client for your Django applications

Dj_sentry This Django application intialize Sentry SDK to your Django application. How to install You can install this packaging by using: pip install

Gandi 1 Dec 09, 2021
A simple Django middleware for Duo V4 2-factor authentication.

django-duo-universal-auth A lightweight middleware application that adds a layer on top of any number of existing authentication backends, enabling 2F

Adam Angle 1 Jan 10, 2022
This is a Django app that uses numerous Google APIs such as reCAPTURE, maps and waypoints

Django project that uses Googles APIs to auto populate fields, display maps and routes for multiple waypoints

Bobby Stearman 57 Dec 03, 2022
Yummy Django API, it's the exclusive API used for the e-yummy-ke vue web app

Yummy Django API, it's the exclusive API used for the e-yummy-ke vue web app

Am.Chris_KE 1 Feb 14, 2022
Customize the behavior of django.contrib.auth permissions.

Customizando o comportamento do django.contrib.auth. O que queremos? Não criar as permissões padrões automaticamente (add, delete, view, read). Criar

Henrique Bastos 7 Nov 26, 2022
REST API con Python, Django y MySQL (GET, POST, PUT, DELETE)

django_api_mysql REST API con Python, Django y MySQL (GET, POST, PUT, DELETE) REST API con Python, Django y MySQL (GET, POST, PUT, DELETE)

Andrew 1 Dec 28, 2021
Agenda feita usando o django para adicionar eventos

Agenda de Eventos Projeto Agenda com Django Inicio O projeto foi iniciado no Django, usando o models.py foi adicionado os dados dos eventos e feita as

Bruno Fernandes 1 Apr 14, 2022
A small Django app to easily broadcast an announcement across a website.

django-site-broadcasts The site broadcast application allows users to define short messages and announcements that should be displayed across a site.

Ben Lopatin 12 Jan 21, 2020
Simple web site for sharing your short stories and beautiful pictures

Story Contest Simple web site for sharing your short stories and beautiful pictures.(Cloud computing first assignment) Clouds The table below shows cl

Alireza Akhoundi 5 Jan 04, 2023
Exemplo de biblioteca com Django

Bookstore Exemplo de biblioteca feito com Django. Este projeto foi feito com: Python 3.9.7 Django 3.2.8 Django Rest Framework 3.12.4 Bootstrap 4.0 Vue

Regis Santos 1 Oct 28, 2021