2024-02-05 Django REST Framework and Vue versus Django and HTMX

HTMX and Django

HTMX has a reputation of a being “JavaScript framework for people who hate JavaScript”. It’s rapidly gaining popularity due to its lightweight and ease of use. If you’ve used any frontend framework before, it has an entirely different feeling to it – it’s less a framework and more of HTML on steroids. When using HTMX, you can easily achieve dynamic page rendering just by using a handful of HTMX-specific attributes directly in HTML.

The core attributes allow you to set an HTTP method and URL for the request (e.g., hx-put), set what event is going to trigger it (hx-trigger), and set the element that’s going to be altered with the response (hx-target).

The easiest way to work with HTMX and Django is to heavily intertwine them. Unlike the Vue and DRF pairing, where each framework can be swapped out independently, you can’t just unplug Django or HTMX and replace it with something else (at least not easily).

On the one hand, the Django code intended for HTMX interactions differs from regular Django code. Conversely, HTMX is embedded directly within Django templates, not existing as separate files. Once you decide to use that combination, replacing either tool with something else would require a complete rewrite.

On the other hand, using plain Django and deciding you need a little more interactivity along the way poses no problem for the lightweight HTMX. Your whole project could rely solely on Django, and adding a single HTMX functionality after a few months would require little overhead.

Let’s see what accomplishing the same thing – a simple password generator with Django and HTMX – looks like.

HTMX is simply included in Django, meaning there are no specific HTMX files. Views and URLs look exactly like you’re used to in plain Django: