'Getting error not found url while making post request to specific url with htmx in Django

I am making like function to my blog without page refreshing. But getting error [06/Apr/2022 20:48:26] "POST /like/post/4/ HTTP/1.1" 404 3945 Here what I do


base.html with htmx settings

<!-- Load from unpkg -->
<script src="https://unpkg.com/[email protected]"></script>
<script>
    document.body.addEventListener('htmx:configRequest', (e) => {
        e.detail.headers['X-CSRFToken'] = '{{ csrf_token }}';
    })
</script>

views.py

def add_like_post(request, pk):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    post.likes.add(request.user)
    return HttpResponseRedirect(post.get_absolute_url())

urls.py

urlpatterns += [
    path('like/post/<int:pk>/', add_like_post, name='like-post'),
]

post-detail.html

{#<form method="post" action="{% url 'like-post post.id %}">{% csrf_token %}#}
     <button hx-post="{% url 'like-post' post.id %}" hx-target="#likes" id="likes"  hx-swap="outerHTML" class="btn btn-block btn-outline-secondary btn-lg mb-2 mx-auto" name="post_id" value="{{ post.id }}"><i class="fa fa-thumbs-up"> L i k e - {{ post.number_of_likes }}</i></button>
{# </form>#}

It works fine when I remove htmx settings from button and adding type='submit' and also uncommenting form. Is there are anything which I did wrong



Solution 1:[1]

The button element is not a form element so HTMX won't include it in the post request. However you already have the post_id data in the target URL, so you can just use that in the view function:

post = get_object_or_404(Post, id=pk)

Or, you can put a hidden element with the post_id and include it in the request via hx-include attribute.

<input type="hidden" name="post_id" value="{{ post.id }}" />
<button hx-post="{% url 'like-post' post.id %}" 
        hx-target="#likes" 
        id="likes"  
        hx-swap="outerHTML"
        hx-include="[name='post_id']"
        class="btn btn-block btn-outline-secondary btn-lg mb-2 mx-auto">
    <i class="fa fa-thumbs-up"> L i k e - {{ post.number_of_likes }}</i>
</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dauros