I want to change the widget type of my many2many relationship to "FilteredSelectMultiple"
I learned from other questions and the documentation that this should do the trick
admin.py
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.db import models
from django import forms
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
forms.ModelMultipleChoiceField: {'widget': FilteredSelectMultiple},
}
Unfortunatly nothing changes in the admin pages. Can anybody help?
Your formfield_overrides
isn't having any effect because you should use the model field, i.e. models.ManyToManyField
instead of the form field, forms.MultipleChoiceField
. However, simply switching the key to models.ManyToManyField
won't work, because the widget should be instantiated with the field name and a boolean is_stacked
.
There are a couple of other approaches:
To use a FilteredSelectMultiple
for individual fields, use the filter_horizonal
or filter_vertical
options.
class MyModelAdmin(admin.ModelAdmin):
filter_horizontal = ('my_m2m_field',)
To override the widget for all many to many fields, you could override formfield_for_manytomany
.
from django.contrib.admin import widgets
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_manytomany(self, db_field, request, **kwargs):
vertical = False # change to True if you prefer boxes to be stacked vertically
kwargs['widget'] = widgets.FilteredSelectMultiple(
db_field.verbose_name,
vertical,
)
return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
Don't forget to register your model with your model admin.
admin.site.register(MyModel, MyModelAdmin)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With