Home > OS >  unable to send post request using HTMX Django
unable to send post request using HTMX Django

Time:01-01

I'm trying to create a CRUD page using django HTMX and unable to send POST request. hx-post sends a GET request instead of POST request.

my Role Models is as follows:

class Role(models.Model):
    name = models.CharField(max_length=200)

I'm creating the form using Cripsy Forms as follows

class RoleForm(forms.ModelForm):
    class Meta:
        model = Role

      fields = ('name', )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.fields['name'].label = "Role"

        self.helper.add_input(Submit('add_new_Role', 'Add', css_class='role_button'))
        self.helper.layout = Layout(
            Row(
                Column('name'),
            )
        )

I'm using the form in my template like this :

{% extends 'main.html' %}
{% load crispy_forms_tags %}

{% block content %}
<div >
  <div >
    <div >
      {% crispy role_form %}
    </div>
  </div>
</div>
<div id="role_list">
  {% include 'role_list.html' %}
</div>


{% endblock %}


{% block javascript %}
<script type="text/javascript">
  $(document).ready(function(){
    $("form").removeAttr("method");
    $('.role_button').attr("hx-post", '{% url "role_add" %}');
    $('.role_button').attr('hx-target', '#role_list');

  });
</script>

{% endblock %}

The CDN link is added in the main.html file.

My understanding is that clicking the ADD button should trigger a POST request. However GET request is initiated, which makes me feel like the HTMX part did not work at all

CodePudding user response:

I found the solution after a too many trial and errors. Turns out Django Crispy forms create an input with type='submit' to create the submit button

however, hx-post works only if you have a button with type='submit' instead of input in order to submit the form

CodePudding user response:

The typical way to do this is to add the hx-post and ht-target attributes to the form element, not the submit button. This will cause HTMX to intercept the submit event on the form, and submit the entire form as an AJAX request.

See the Triggering Requests documentation:

By default, AJAX requests are triggered by the "natural" event of an element:

  • form is triggered on the submit event
  • Related