user2919162
user2919162

Reputation: 69

Django: disappearing filter_horizontal after overriding a form field

I have a many2many field in model:

models.py

pages = models.ManyToManyField(Page, verbose_name='Pages', blank=True)

And for admin interface filter_horizontal works just fine:

admin.py

filter_horizontal = ['pages',]

But when i overriding this field, using forms.Modelform (for changing queryset) - in interface it begins to show like a simple <select> field:

forms.py

class BannerAdminForm(forms.ModelForm):
    pages = forms.ModelMultipleChoiceField(queryset=Page.objects.filter(publisher_is_draft=0), label='Pages')

    class Meta:
        model = Banners

admin.py

class BannersAdmin(admin.ModelAdmin):
    form = BannerAdminForm
    filter_horizontal = ['pages',]

Is there any solution for this problem? I looked for some special widgets for ModelMultipleChoiceField, but don't find anything.

Upvotes: 1

Views: 657

Answers (2)

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53998

This doesn't address the actual issue but is an alternative approach to setting the queryset:

class BannerAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
         super(BannerAdminForm, self).__init__(*args, **kwargs)
         self.fields['pages'].queryset = Page.objects.filter(publisher_is_draft=0)

    class Meta:
        model = Banners

Upvotes: 1

CJ4
CJ4

Reputation: 2535

Take a look at this snippet, you can specify the widget of the field as FilteredSelectMultiple

Upvotes: 0

Related Questions