Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form

后端 未结 2 1317
一向
一向 2020-12-11 07:12

The green plus sign button for adding new instances in the admin form disappears for my MultiSelect field (photos) when I define it in my form. Ie, removing the line with th

相关标签:
2条回答
  • 2020-12-11 07:34

    Yes you are right, you have to wrap your widget with django.contrib.admin.widgets.RelatedFieldWidgetWrapper, which turns out to be a bit complicated since it expects the current admin site as a parameter for initialization! Maybe you will find this post helpful!

    0 讨论(0)
  • 2020-12-11 07:36

    With the help from lazerscience and this post I ended up with the following.

    The ModelAdmin:

    class GalleryAdmin(admin.ModelAdmin):
    
        form = GalleryForm
    
        def __init__(self, model, admin_site):
            self.form.admin_site = admin_site 
            super(GalleryAdmin, self).__init__(model, admin_site)
    

    And my form:

    class GalleryForm(ModelForm):
    
        photos = ThumbnailChoiceField(queryset=Photo.objects.all(), label='Photos', widget=MyWidget(), required=False)
    
        def __init__(self, *args, **kwargs):
            super(GalleryForm, self).__init__(*args, **kwargs)
            rel = ManyToOneRel(self.instance.photos.model, 'id') 
            self.fields['photos'].widget = RelatedFieldWidgetWrapper(self.fields['photos'].widget, rel, self.admin_site) 
    
    0 讨论(0)
提交回复
热议问题