0

I'm developing a Django application in which a lot of models have foreign keys and m2m relationships. This results in many ModelChoiceField being displayed in the Django admin for my models. To make model choice more bearable, I installed the django-select2 app in my project.

I have been trying to implement select2 in the inline forms the admin site displays when editing related objects, but the form doesn't render the ModelSelect2Widget (it renders a simple select; it doesn't even include the select2 library).

What I tried was creating a ModelForm in forms.py overriding the relevant fields widgets, then, using inlineformset_factory, had a variable holding the factory class. Lastly, in admin.py, added my custom inline formset using the formset property of the InlineModelAdmin class.

forms.py

class FichaTecnicaForm(forms.ModelForm):
    class Meta:
        model = models.FichaTecnica
        exclude = ('pelicula',)
        widgets = {
            'responsable': ModelSelect2Widget,
            'cargo': ModelSelect2Widget,
            'pais': ModelSelect2Widget
        }
FichaTecnicaInline = inlineformset_factory(models.Pelicula, models.FichaTecnica, form=FichaTecnicaForm)

admin.py

class FichaTecnicaInline(admin.TabularInline):
    model = models.FichaTecnica
    formset = forms.FichaTecnicaInline
    extra = 0
# Some other code here

# This is where the inlines are invoked
class PeliculaAdmin(admin.ModelAdmin):
    inlines = [
        FichaTecnicaInline,
        # some other inlines, not relevant...
    ]

I was expecting that the inline form set would display the select2 widget for the model choice, but instead it displays a standard select widget.

Thank you very much in advance for you help!

scr1ptom
  • 11
  • 3

1 Answers1

0

I think there is an error in your code where your FichaTecnicaInline class is overwritten by your admin class definition.

Maybe the formset class created by inlineformset_factory, which uses your custom form is being overwritten by defaults from admin.TabularInline. I think the first thing to try is giving them different names.

Atcrank
  • 439
  • 3
  • 11
  • I am going to test that tomorrow (I don't have that code in a repo yet to pull from home), that might be it. I thought there wouldn't be any name compatibility issues since one is namespaced (`forms.FichaTecnicaInline`) and the class definition is not. Anyway, I'll get back to this when I get the chance to test it. Many thanks!! – scr1ptom Apr 26 '19 at 02:12
  • I just tried changing the reference for `FichaTecnicaInline` to `FichaTecnicaInlineFormSet` and it still doesn't work. Thanks anyway for your time and suggestion! – scr1ptom Apr 26 '19 at 14:38
  • Sorry, you were probably right about the namespacing, which I hadn't considered. – Atcrank Apr 29 '19 at 00:40