Search code examples
djangohtmxdjango-select2

Issue with how the django_easy_select2 library is initialized or bound to the HTML element that I'm replacing with htmx


I've successfully used htmx to handle a AJAX call to replace part of an django template form. Please see the question I posted on this here Django and HTMX for dynamically updating dropdown list in form.field . But, the form element being replaced is a multiple drop down list, which uses the django_easy_select2 library to render the drop down list nicely, and when replaced by htmx it isn't including any of the extra html elements built by django_easy_select2. Grateful if someone could explain how I solve this.

A good option would seem to be to reinitialize the django_easy_select2 library after the htmx replacement occurs. Grateful for advice on how I do this.


Solution

  • I haven't used django_easy_select2 but I have used HTMX together with django-select2 and other javascript based plugins and what you have to do is call the initialization scripts after the DOM has settled:

    method 1:

    Let's say this is your partial html that gets rendered for the HTMX response:

    <div>
    {{form}}
    </div>
    
    {{form.media}} # also add the initialization scripts (they're usually in form.media).
    
    method 2:

    Add this script at the end of your body (not partials, the event should be added when the page loads).

    <script type="text/javascript">
        document.body.addEventListener('htmx:afterSettle', async (event) => {
            // Call the initialization scripts here so they run when the DOM has settled after a swap
            // In my case this was:
            $('.django-select2').djangoSelect2()
        });
    </script>