HTMX for messages from the backend in django

Viewed 839

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!

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.

Related