Freelancing for Pale Blue

Looking for flexible work opportunities that fit your schedule?

Freedom for HTML input elements using htmx

Django Sep 23, 2022

Coming from the world of the more "traditional" Django development, I was used to communicating with the backend using HTML forms.

Whenever I needed to include something in my GET or POST request, be it data entered into a text box or hidden inputs containing values, I would wrap them into a <form> element. And for the most part, this technique works.

But there are cases where this might be problematic or at least annoying. Problematic might be in case the HTML structure is forcing you to have the <input> elements wrapped in a <form> element and this makes impossible some positioning or styling configuration. Annoying might be just the fact that you are forced to have deep layers of hierarchy just to fulfill this "limitation" of HTML.

But fear not. htmx is here to save the day. Using this JS library can simplify your Django front-end work significantly, and this is just one use case. What you can do is essentially to specify which <input> elements to include in a GET or POST request, no matter where they are placed in the DOM.

This gives complete freedom to structure your page and place those <input> elements exactly where you want them to be based on your mocks or designs.

<div class="column">
    <input class="input" name="item_quantity" type="number" />

<div class="column">
    <a hx-boost="true"
       href="{% url 'submit_view' %}">

This simple snippet showcases an example of this. The <input> element is not wrapped in a <form>. Nevertheless, its value is included in the request made to the backend.

  • hx-boost: This "converts" this link to an htmx-powered request. It will not cause a full page to reload, rather the result of the GET request will replace the body of the website.
  • hx-include: This is how you include the <input> elements in the GET request. In the backend, you can access the value of that input using request.GET.get('item_quantity', 1)

Hopefully, you learned yet another way of passing data to your Django backend without using HTML forms, but by using htmx.

Happy coding!


Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.