Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 the definition (photos = ...) makes the plus sign appear. However, in order to use a custom Field/Widget I need to figure this out.

class GalleryForm(ModelForm):

    photos = ModelMultipleChoiceField(queryset=Photo.objects.all(), label="Photos")

    def __init__(self, *args, **kwargs):
        super(GalleryForm, self).__init__(*args, **kwargs)

I've peeked at the Django source code and it seems like I have to wrap my widget in a RelatedFieldWidgetWrapper, but I haven't quite gotten my head around it. Any help is apprecietad!

like image 864
Reimund Avatar asked Sep 11 '10 22:09

Reimund


People also ask

How do you make a field required in Django admin?

Making Fields Required In Django Admin In order to make the summary field required, we need to create a custom form for the Post model. I am making them on the same file you can do this on a separate forms.py file as well.


1 Answers

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:

from django.contrib.admin.widgets import RelatedFieldWidgetWrapper


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) 
like image 154
Reimund Avatar answered Sep 25 '22 07:09

Reimund