Why HTMX Might Be the Perfect Match for Django Developers

Django excels at leveraging its Object-Relational Mapper (ORM), forms, routing and templating system to build robust web applications. However, when it comes to the frontend, things can get a bit clunky and outdated.

Unlike Ruby on Rails’ Turbolinks or Laravel’s Livewire, Django lacks a built-in solution for dynamic frontend interactions. This leaves developers with two main options:

  1. Full-fledged Single-Page Applications (SPAs): While powerful, SPAs often lead to complex, hard-to-maintain codebases with lengthy development cycles and increased hosting costs. Additionally, SPAs can clash with Django’s strengths.

  2. Vanilla Javascript/jQuery: This approach, while seemingly simpler, becomes cumbersome for larger projects. Scaling and maintaining spaghetti code with tons of boilerplate becomes a nightmare.

You probably don’t need a SPA

Nowdays, it seems like every new project is built as a Single Page Application (SPA) with React, Vue or Angular and I mean everything :

  • You need a simple blog? SPA

  • You need a dashboard to manage your users? SPA

  • You need a landing page? SPA

Single page applications are great when use correctly, they were created to solve a problem, the problem of complex web applications that require a lot of interactivity and frequent updates, DOM interactions and UI components re-rendering and reusability.

Some of the web applications we use everyday like Gmail, Google Docs and Trello are perfect examples of when to use a SPA, but that comes with a cost, a cost that is not always easy to understand, from increased complexity to slower loading times and SEO challenges, spas are often not the best choice.

HTMX: A Breath of Fresh Air

HTMX is the most enjoyable piece of technology I’ve come across in a long time (since Django ;) ), allowing you to integrate AJAX functionality, interactivity and modern feel into your Django project without writing a single line of Javascript (although you have the option to if needed).

Here’s the beauty: instead of returning an entire HTML page, you can return just the specific portion (a partial) that needs updating.

HTMX then handles the DOM manipulation for you while the state remains on the server, you keep writing Django views and templates, but now you can add some HTMX attributes to your HTML and you have a dynamic web application.

For developers accustomed to JSON responses and manual DOM updates with Javascript, HTMX might feel counterintuitive at first. Transitioning from JSON to HTML responses can be a slight adjustment, but the benefits quickly become apparent especially when you are already familiar with Django.

You already know how to use HTMX

One of the best things about HTMX is that you already know how to use it. If you know how to write Django views, how to return HTML responses and write basic HTML, you have 95% of the knowledge you need.

Once you grasp the basics of HTMX, how the flow of data works, the concept of partials and how to use the various attributes, you’ll be able to build dynamic, interactive web applications in no time.

You can check the end of the article for some resources to get started with HTMX.

Real-World Example: Streamlining My Startup

Instead of delving into the technical details of HTMX, let me share my experience migrating thousands of lines of Javascript code to HTMX in my hospitality SaaS startup.

Initially, the app (built with Django) relied heavily on Javascript for dynamic interactions. We initially opted for VueJS for the web app frontend and Flutter for the mobile apps. This led to using the same API endpoints for both the web and mobile app (Flutter) with VueJS managing the state and DOM for the web app.

The Roadblocks Emerged

This approach quickly revealed several issues:

  • Code Duplication: Significant code duplication existed between the backend and the frontend, logic was duplicated in Django and VueJS, leading to inconsistencies and bugs.

  • Underutilized Django Features: By managing state and DOM with VueJS, we missed out on Django’s strengths:

    • Django forms and built-in validation
    • Powerful template tags and filters
    • Streamlined class-based and function-based views
    • URL routing and reverse URL resolution
  • Complexity: Managing state with VueJS led to complex code, especially when handling form submissions, fetching data, and updating the DOM, it was also hard to integrate with Django’s templating system.

  • Harder to test and maintain: With the frontend logic split between VueJS and Django, testing became more complex and often not possible since I had to test the frontend and backend separately, it’s worth mentioning that I was the only developer on the project and far from being a frontend expert.

These might seem like minor details, but they significantly impact developer productivity and experience.

The HTMX Solution

With HTMX, I removed every line of Javascript in a span of a few months, the API endpoints sole purpose was to be used by the partner integrations and the mobile apps, the web app was now a traditional and boring (in the good way) Django app with HTMX and classic Django views.

The benefits were immediate:

  • Reduced Code Volume: The codebase shrank significantly, since I had all the state and logic in Django backend, I was able to remove more than 3000 lines of Javascript code, so long Vuex, Axios, and VueJS.

  • Better decoupling: The mobile apps and the web app were now completely decoupled, the mobile apps is using the same API endpoints as before, but I can now change the web app without affecting the mobile apps and the APIS are tailored for the mobile apps, making them more efficient and simpler to write and use

  • Faster Development: Before using HTMX when creating a new page, I had to write the backend logic, the frontend logic, the API endpoints, I had to create some data representation in the frontend, handle the validation, the error messages, the loading states, the success states etc… now I just have to write the backend logic and add some HTMX attributes to the frontend and I’m done.

  • Better Testing: Since everything is now pure Python with Django I can improved and add more tests to my codebase, with JS I must confess I was not testing the frontend at all…

  • Better User Experience: The user experience is now better, the faster loading times, the better error handling, validation, and loading states make the app feel more responsive and less clunky.

HTMX + Django ❤️

The benefits of using HTMX go beyond reduced code volume, while this alone is a significant win, let’s see what other benefits we get.

One of the biggest advantages of HTMX is its ability to seamlessly integrate with Django’s built-in features. Here’s how:

  • Forms and Validation: Say goodbye to duplicating validation logic! HTMX works flawlessly with Django forms, ensuring data integrity and a consistent user experience. Django handles the validation on the server-side, while HTMX updates the form and error messages dynamically without a single line of Javascript.
  • Template Tags and Filters: Django’s rich set of template tags and filters becomes readily available for use within your HTMX responses. This empowers you to format data, generate dynamic content, and leverage Django’s templating power to its full potential.
  • Class-Based and Function-Based Views: HTMX integrates beautifully with Django’s view system. Whether you prefer class-based or function-based views, HTMX works perfectly, you can focus on core application logic without worrying about complex frontend interactions.
  • URL Routing: HTMX does not interfere with Django’s URL routing system. You can continue to define your URLs in Django’s urls.py and use them as usual. This means that powerful features like reverse URL resolution, namespaced URLs, internationalization, and more remain available, which is something that can be challenging with SPAs.

Developers can leverage their existing Django knowledge and stay within the framework’s ecosystem.

But there is more

Using HTMX with Django offers several advantages over a Single Page Application (SPA) approach:

  • Simplicity: HTMX does not require developers to learn about state management libraries, complex build tools or AJAX request handling. Instead, it leverages the existing Django server-side logic and templating system, that any Django developer is already familiar with.

  • Seamless Integration: HTMX seamlessly integrates with Django’s, no setting up complex API endpoints, or diving into the intricacies of client-side routing. This is something that can be challenging with SPAs especially when it comes to authentication, CSRF protection, and deployment.

  • No state management: HTMX does not require developers to manage complex state management libraries like Redux or Vuex. Instead, it relies on the server to manage the state, for anyone who has previously worked with state management libraries, that alone is a huge win.

  • Progressive Enhancement: With HTMX, you can progressively enhance your Django applications by adding dynamic interactions to traditional server-rendered pages. You could build a kind of hybrid application where some parts are dynamic while others remain static, providing a better user experience without sacrificing SEO.

  • SEO Friendliness: Since HTMX works with traditional server-rendered Django views, it inherently supports search engine optimization (SEO) by serving fully-rendered HTML content to web crawlers. This can be advantageous for applications where search engine visibility is important.

When not to use HTMX

While the benefits of HTMX cannot be understated, there are some projets and use cases where HTMX is not the best choice.

  • If you are building a complex application like a video editor, a spreadsheet or anything that requires a lot of interactivity and frequent update and UI components, HTMX will have poor performance compared to a SPA like React or Vue.

  • If you need offline support, HTMX does not support offline, though you can use service workers to cache the pages, it is kind of a hack and does not work well.

Ressources

The best ressource is obviously the HTMX documentation, it is well written and covers everything you need to know to get started, but here are some other ressources that can help you get started:

  • Hypermedia Systems - Written by the creator of HTMX, this free book covers the principles behind HTMX, the hypermedia concept, and how to build web applications with HTMX.

  • FULL Introduction To HTMX Using Golang - A 2hour tutorial by ThePrimeagen on how to use HTMX with Golang, while it is not Django, ThePrimeagen does a great job explaining the concepts behind HTMX with humor.

  • Django & HTMX Playlist (39 videos) - By the Youtuber BugBytes, this playlist covers a lot of use cases and how to use HTMX with Django.

Conclusion

Overall, using HTMX with Django offers a pragmatic approach to adding dynamic behavior to your web applications while maintaining the benefits of server-side rendering and leveraging the power of the Django framework.

I have successfully migrated my startup’s frontend to HTMX, and saved countless hours of development time. The codebase is now cleaner, more maintainable, and easier to work with.

I truly believe that HTMX is the perfect match for Django developers and will be the next big thing in the Django ecosystem. Give it a try, and you might be surprised by how much it simplifies your frontend development workflow.