How to Implement HTML Minification in Your Django Project Using Middleware

HermantoXYZ
1 min readAug 2, 2024

--

If you have a folder structure like project and within it, you have a subfolder middleware, and you want to add HTMLMinifyMiddleware from the middleware.py file within that subfolder, you can do it as follows:

  1. Folder Structure:

Ensure your folder structure looks like this:

project/
├── __init__.py
├── settings.py
├── urls.py
├── wsgi.py
├── middleware/
├── __init__.py
├── middleware.py

2. Create New Middleware:

Create or edit the middleware.py file inside the inviteku/middleware folder and add the following code:

import re

class HTMLMinifyMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
response = self.get_response(request)

if 'text/html' in response['Content-Type']:
response.content = self.minify_html(response.content.decode('utf-8'))
response['Content-Length'] = len(response.content)

return response

def minify_html(self, html):
html = re.sub(r'\n\s*', '', html)
html = re.sub(r'\s{2,}', ' ', html)
html = re.sub(r'>\s<', '><', html)
return html

Add Middleware to Django Settings:

Edit the settings.py file and add the new middleware to the MIDDLEWARE list as follows:

MIDDLEWARE = [
# Other middleware...
'project.middleware.middleware.HTMLMinifyMiddleware',
# Other middleware...
]

--

--

No responses yet