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 Advance DumpData

Django Advance Dumpdata Django Manage Command like dumpdata but with have more feature to Output the contents of the database from given fields of a m

EhsanSafir 7 Jul 25, 2022
Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.

django-mongonaut Info: An introspective interface for Django and MongoDB. Version: 0.2.21 Maintainer: Jazzband (jazzband.co) This Project is Being Mov

Jazzband 238 Dec 26, 2022
Docker django app

Hmmmmm... What I should write here? Maybe "Hello World". Hello World Build Docker compose: sudo docker-compose build Run Docker compose: sudo docker-

Andrew 0 Nov 10, 2022
Intellicards-backend - A Django project bootstrapped with django-admin startproject mysite

Intellicards-backend - A Django project bootstrapped with django-admin startproject mysite

Fabrizio Torrico 2 Jan 13, 2022
A standalone package to scrape financial data from listed Vietnamese companies via Vietstock

Scrape Financial Data of Vietnamese Listed Companies - Version 2 A standalone package to scrape financial data from listed Vietnamese companies via Vi

Viet Anh (Vincent) Tran 45 Nov 16, 2022
Django REST Client API

Django REST Client API Client data provider API.

Ulysses Monteiro 1 Nov 08, 2021
Auth module for Django and GarpixCMS

Garpix Auth Auth module for Django/DRF projects. Part of GarpixCMS. Used packages: django rest framework social-auth-app-django django-rest-framework-

GARPIX CMS 18 Mar 14, 2022
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 02, 2023
Chatbot for ordering and tracking a Pizza.

Pizza Chatbot To start the app, follow the below steps: Clone the repo using the below command: git clone Shreya Shah 1 Jul 15, 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
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

lhy 139 Dec 05, 2022
Add Chart.js visualizations to your Django admin using a mixin class

django-admincharts Add Chart.js visualizations to your Django admin using a mixin class. Example from django.contrib import admin from .models import

Dropseed 22 Nov 22, 2022
🔃 A simple implementation of STOMP with Django

Django Stomp A simple implementation of STOMP with Django. In theory it can work with any broker which supports STOMP with none or minor adjustments.

Juntos Somos Mais 32 Nov 08, 2022
📊📈 Serves up Pandas dataframes via the Django REST Framework for use in client-side (i.e. d3.js) visualizations and offline analysis (e.g. Excel)

Django REST Pandas Django REST Framework + pandas = A Model-driven Visualization API Django REST Pandas (DRP) provides a simple way to generate and se

wq framework 1.2k Jan 01, 2023
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
Custom Django field for using enumerations of named constants

django-enumfield Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. Installation Currently

5 Monkeys 195 Dec 20, 2022
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

Daniel Feldroy 10k Dec 31, 2022
Django React Flight Rezervation

Django Intro & Installation python -m venv venv source ./venv/Scripts/activate pip install Django pip install djangorestframework pip install python-d

HILMI SARIOGLU 2 May 26, 2022
GeoDjango provides geospatial extensions to the Django web dev framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. All documentation is in the "docs" directo

Paul Smith 20 Sep 20, 2022
Strict separation of config from code.

Python Decouple: Strict separation of settings from code Decouple helps you to organize your settings so that you can change parameters without having

Henrique Bastos 2.3k Jan 04, 2023