Django: AJAX ManyToManyField in admin

后端 未结 3 1994
礼貌的吻别
礼貌的吻别 2021-02-10 03:19

I want to display ManyToManyFields in admin just like filter_horizontal does, but populate the options as the user types into the filter field. There a

3条回答
  •  时光取名叫无心
    2021-02-10 03:33

    If the UI of Select2 appeals to you, you could use Django-Select2 in the Admin.

    For m2m it might work like you suggested:

    class MyAdmin(admin.ModelAdmin):
        formfield_overrides = {
            models.ManyToManyField: {'widget': ModelSelect2MultipleWidget},
        }
    
        # required to make jquery available to select2
        # has to be loaded via Admin class (and not via widget or form class) for correct order in output
        class Media:
            js = ("ext/js/jquery.min.js",)
    

    Ajax works by adding the following URL pattern to urls.py:

    # if using ModelWidget
    url(r'^select2/', include('django_select2.urls')),
    

    Of course, you can also provide your own view implementations, see the documentation linked above.

    I'm currently not using it for m2m but for reverse foreign key relations, so I'm using it in a custom form in the Django admin, instantiating the widget explicitly. Thus, in case it's not working with formfield_overrides, the long way would be an option.

提交回复
热议问题