Search code examples
djangohtmx

How to attach HTMX parameters to a django input form


I am trying to implement an HTMX autosearch function to an input created by a django form. When I inspect the element on the page, the htmx tags are all present. However, the htmx never intializes and it never goes to the views endpoint. The code for the django input form is as follows:

widget_attrs_nha_autosearch = {
    'class': 'form-control',
    'data-user-entry': 1,
    'disabled': value.get('read_only'),
    'hx-post': "{% url 'django_p:n-autosearch' %}",
    'hx-target': '#results',
    'hx-trigger': "keyup changed delay:500ms"
}


if value.get('label') == 'n_override':
    self.fields[field] = forms.CharField(
        initial=value.get('default', ''),
        label=value.get('label'),
        max_length=value.get('max_length'),
        required=required,
        widget=forms.TextInput(attrs=widget_attrs_n_autosearch),
        validators=value.get('validators', []))

When I attempt to create the htmx code on its own in html, it works just fine. However, I need the code to be created in this manner in order to properly trigger something on the backend. The HTMX code on its own is as follows:

{% csrf_token %}
<div class="d-flex justify-content-end mb-4">
       <input type="input"
              hx-post="{% url 'django_p:n-autosearch' %}"
              hx-target='#results'
              hx-trigger="keyup changed delay:500ms"
              name="search"
              class="d-flex flex-grow-1 flex-column p-3 border border-secondary rounded m-2"
              style="overflow: auto;
                     min-width: 0;
                     min-height: 0"
              placeholder=""
              id='id_n_override' />
</div>
<div id="results"></div>

Am I missing something?


Solution

  • I suspect you are trying to use a template evaluation in your view to create the form, and when the form is evaluated it is being done separately from the template. Rather than use the template filter {% url %}, try reverse() instead, eg,

    Rather than 'hx-post': "{% url 'django_p:n-autosearch' %}",

    try 'hx-post':reverse('django_p:n-autosearch')