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
Full-text multi-table search application for Django. Easy to install and use, with good performance.

django-watson django-watson is a fast multi-model full-text search plugin for Django. It is easy to install and use, and provides high quality search

Dave Hall 1.1k Dec 22, 2022
WeatherApp - Simple Python Weather App

Weather App Please star this repo if you like ⭐ It's motivates me a lot! Stack A

Ruslan Shvetsov 3 Apr 18, 2022
A django model and form field for normalised phone numbers using python-phonenumbers

django-phonenumber-field A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonen

Stefan Foulis 1.3k Dec 31, 2022
This Django app will be used to host Source.Python plugins, sub-plugins, and custom packages.

Source.Python Project Manager This Django app will be used to host Source.Python plugins, sub-plugins, and custom packages. Want to help develop this

2 Sep 24, 2022
With Django Hijack, admins can log in and work on behalf of other users without having to know their credentials.

Django Hijack With Django Hijack, admins can log in and work on behalf of other users without having to know their credentials. Docs 3.x docs are avai

1.2k Jan 05, 2023
Django + AWS Elastic Transcoder

Django Elastic Transcoder django-elastic-transcoder is an Django app, let you integrate AWS Elastic Transcoder in Django easily. What is provided in t

StreetVoice 66 Dec 14, 2022
This is raw connection between redis server and django python app

Django_Redis This repository contains the code for this blogpost. Running the Application Clone the repository git clone https://github.com/xxl4tomxu9

Tom Xu 1 Sep 15, 2022
Show how the redis works with Python (Django).

Redis Leaderboard Python (Django) Show how the redis works with Python (Django). Try it out deploying on Heroku (See notes: How to run on Google Cloud

Tom Xu 4 Nov 16, 2021
A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, celery and redis.

Django Channels Websocket Chatbot A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, c

Yunbo Shi 8 Oct 28, 2022
Silk is a live profiling and inspection tool for the Django framework.

Silk is a live profiling and inspection tool for the Django framework. Silk intercepts and stores HTTP requests and database queries before presenting them in a user interface for further inspection:

Jazzband 3.7k Jan 02, 2023
Organize Django settings into multiple files and directories. Easily override and modify settings. Use wildcards and optional settings files.

Organize Django settings into multiple files and directories. Easily override and modify settings. Use wildcards in settings file paths and mark setti

Nikita Sobolev 940 Jan 03, 2023
A Django GraphQL (Graphene) base template

backend A Django GraphQL (Graphene) base template Make sure your IDE/Editor has Black and EditorConfig plugins installed; and configure it lint file a

Reckonsys 4 May 25, 2022
An extremely fast JavaScript and CSS bundler and minifier

Website | Getting started | Documentation | Plugins | FAQ Why? Our current build tools for the web are 10-100x slower than they could be: The main goa

Evan Wallace 34.2k Jan 04, 2023
Ugly single sign-on for django projects only

django-usso Ugly single sign-on for django projects only. Do you have many django apps with different users? Do you want to use only one of those apps

Erwin Feser 1 Mar 01, 2022
A simple demonstration of how a django-based website can be set up for local development with microk8s

Django with MicroK8s Start Building Your Project This project provides a Django web app running as a single node Kubernetes cluster in microk8s. It is

Noah Jacobson 19 Oct 22, 2022
Automatically upgrade your Django projects.

django-upgrade Automatically upgrade your Django projects. Installation Use pip: python -m pip install django-upgrade Python 3.8 to 3.10 supported. Or

Adam Johnson 525 Dec 29, 2022
Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)

django-cors-headers A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django a

Adam Johnson 4.8k Jan 03, 2023
No effort, no worry, maximum performance.

Django Cachalot Caches your Django ORM queries and automatically invalidates them. Documentation: http://django-cachalot.readthedocs.io Table of Conte

NoriPyt 980 Jan 06, 2023
🔥 Campus-Run Django Server🔥

🏫 Campus-Run Campus-Run is a 3D racing game set on a college campus. Designed this service to comfort university students who are unable to visit the

Youngkwon Kim 1 Feb 08, 2022
Bootstrap 4 integration with Django.

django-bootstrap 4 Bootstrap 4 integration for Django. Goal The goal of this project is to seamlessly blend Django and Bootstrap 4. Requirements Pytho

Zostera B.V. 980 Dec 29, 2022