Search code examples
djangohtmx

Can't get two elements to update while using Django and HTMX


I'm trying to create a car pool where I use HTMX in my Django project to make it work. The CarPool model consist of two FK. One FK is "City", and the other is "Car". I have it somewhat working. So within my two tables (one table with all the cars that have no city attached, and the other table displaying all the cars attached to the city that has been clicked), I'm able to use hx-post to add the car, and same to remove the car with the clicked city. But I don't get the lists to update after they are clicked.

I have tried different ways of using hx-oob-swap but since I'm fairly new with both Django and HTMX I'm not sure where to exactly use it.

See attached pictures. So picture "notclicked", the left table shows all cars with no city, and the right table displays cars with "Chicago" as a FK. notclicked

Picture "clicked" I have now clicked on the car MMW 331 from the left table, and it adds it to the right table which is good, but then when I click on it, I want it also to be removed from the left table (same goes if I delete a car from the right table) clicked

Thankful for any help :)

Here is my test-repo from github: github


Solution

  • Personally, I don't see why you can't just make normal request and refresh the whole page.

    Using htmx may seem quite tricky and there're few ways to handle this. Although I like to avoid using oob and prefer the custom tirgger header approach:

    Create 2 endpoints:

    • remove item from left table (POST)
    • right table data fetch (GET)

    Follow the htmx's delete row example to see how the removal should be handled.

    To have the second table refreshed after removing the item, you can attach htmx trigger header to the removal response.

    This requires django-htmx package to be installed (which you'll find useful in general, when working with django + htmx).

    You can read more about htmx custom response headers here.

    So your response will look smth like this:

    return trigger_client_event(
        HttpResponse(''),
        "citySelected",
        after="swap"
    )
    

    This will cause htmx to trigger citySelected event, after delete item response is returned.

    You can then use that event to refresh the right-side table content (or it's tbody) like so:

    <tbody id="filter-cars" hx-get="/list-of-cars/" hx-trigger="citySelected from:body">
    

    This solution may be quite opinionated, but it's one way to get it done.