The default widget for ManyToManyFields in django-admin is difficult to use. I can set filter_horizontal on individual fields and get a much nicer widget.
How can I set filter_horizontal as the default on all ManyToManyFields?
(I’d also be happy with filter_vertical of course.)
I’ve searched around for a solution and didn’t find anything on Google or SO. I can think of how to do this with some meta-programming, but if someone already did this or if it’s in Django somewhere, I’d love to hear about it.
The best way to modify classes defined in pre-existing code is to use a mixin. You need to modify the
formfield_for_manytomanymethod ofModelAdminclass; the method is defined inBaseModelAdmin.Add the following code in a module that’s guaranteed to run when your Django server starts up [a
models.pyof one of your own apps]:Note (27 Aug 2019):
I’m fully aware of how subclassing/inheritance works, and that’s best practice for solving problems like this. However, as I’ve reiterated in the comments below, subclassing will not solve the OP’s problem as stated ie. making
filter_horizontalorfilter_verticalthe default. With subclassing, not only will you need to register your subclass for all your models, you’ll have to unregister each ModelAdmin subclass that’s registered in builtin Django apps and third-party apps you’ve installed, then register your new ModelAdmin subclasses. So for example for Django’s builtin User model …… then repeat similar code for all Django apps and third-party apps you’ve installed. I don’t think this is what the OP wanted, hence my answer.