I wanted to use HTMX to show messages from django backend after a lot of trial and error I ended up with a working solution, that I want to leave behind for anyone looking for it - also, please feel free to post your suggestions. Unfortunately, besides a little example from the htmx-django package, there is almost no tutorial material available. Be sure to check the example out, as it covers some basics specially for django users!
-
1Since you solved the problem, please add an Answer below, containing the info you figured out, and select it as the correct answer. This will help others find this post when looking for similar information! – djangomachine Apr 29 '21 at 21:15
1 Answers
For HTMX we need a little element somewhere in the DOM that HTMX can work (swap for example) with. Place for example a
<div id="msg">
{% include "app/messages-partial.html" %}
</div>
somewhere on your index.html
. Now we want to use this element to fill it with content, if the need arises. Let's say we click a button, that communicates with a view and the answer gets posted. In django the response is created using render
:
class TestView(TemplateView):
template_name = "index.html"
def get(self, request, *args, **kwargs):
...
class_code = """class='alert alert-dismissible fade show'"""
msg_str = """testmessage"""
msg_btn = """<button type='button' class='close' data-dismiss='alert'>x</button>"""
msg = mark_safe(f"""<div {classcode}>{msg_str}{msg_btn}</div>""")
return render(request, "app/messages-partial.html", {"msg": msg})
and a corresponding path
in urls.py
:
path("action/", views.TestView.as_view(), name = "test"),
I created a simple messages-partial.html
:
{% if msg %}
{{ msg }}
{% endif %}
So what I wanted is, when I triggered the the view, the {{ msg }}
gets replaced (swapped) by HTMX to the content of the response. Therefore I implement the HTMX part somewhere else on the index.html
as follows:
<div class="..."
hx-get="/action"
hx-swap="innerHTML"
hx-target="#msg" >
<button class="btn btn-primary">TEST</button>
</div>
The former <div id="msg">...</div>
will swap with {{ msg }}
(and I included the typical django-messages
close button).
Thanks to the htmx discord channel where friendly people shared their knowledge with me.

- 4,555
- 31
- 31
- 45

- 1,070
- 1
- 15
- 41