jazzband / django-polymorphic

Improved Django model inheritance with automatic downcasting

Home Page:https://django-polymorphic.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Issue with Autocomplete Fields in StackedPolymorphicInline.Child Inline

guidolongoni opened this issue · comments

Hello,

I'm encountering an issue related to autocomplete fields within an inline with the class StackedPolymorphicInline.Child.

Summary:

The problem is that the dropdown menus for autocomplete fields appear empty, and no AJAX calls are made.

Description/details:

After analyzing the code, it seems that there might be an incompatibility between the event triggering mechanisms used in the polymorphic_inlines.js file and the callback defined in the Django package's autocomplete.js file.

In polymorphic_inlines.js, the event is triggered using jQuery as follows:

$(document).trigger('formset:added', [row, options.prefix]);

On the other hand, the event is supposed to be received by the callback defined in the Django package's autocomplete.js file, where we find the following code:

document.addEventListener('formset:added', (event) => {
    $(event.target).find('.admin-autocomplete').djangoAdminSelect2();
});

It appears that the autocomplete functionality does not receive this event due to the discrepancy in the triggering mechanism.
In the Django package's inlines.js file, in fact, the same event is triggered using plain JavaScript in the following manner:

row.get(0).dispatchEvent(new CustomEvent("formset:added", {
    bubbles: true,
    detail: {
        formsetName: options.prefix
    }
}));

Versions:

I am using the following versions:

  • Django: 4.2.2
  • django-polymorphic: 3.1.0

Could you please investigate this issue and provide guidance on how to resolve it? Is there a recommended workaround or fix available?

Thank you for your attention to this matter.

Best regards,
Guido Longoni

This is happening for me as well:

  • Django: 4.2.3
  • django-polymorphic: 3.1.0

I'm also seeing this with Django 4.2.6 and django-polymorphic 3.1.0

For the time being I think I've managed to work around this by adding the following JS to the relevant ModelAdmin, which listens for the jQuery formset:added event and dispatches a native event which Django's autocomplete code will pick up:

(function($) {
    $(document).ready(function() {
        /*  Listen for legacy jQuery events triggered by `django-polymorphic`
            and trigger corresponding native event

            issue: https://github.com/django-polymorphic/django-polymorphic/issues/546
        */

        $(document).on('formset:added', function(event, row, prefix) {
            if (!row) return;
            row.get(0).dispatchEvent(new CustomEvent('formset:added', {
                bubbles: true,
                detail: {
                    formsetName: prefix,
                },
            }));
        });
    });
})(django.jQuery || jQuery);