The best way to change the classes defined in existing code is to use mixin . You need to change the formfield_for_manytomany method of the formfield_for_manytomany class; The method is defined in BaseModelAdmin .
Add the following code to the module, which is guaranteed to work when you start your Django server [a models.py one of your own applications]:
from django.contrib.admin.options import ModelAdmin from django.contrib.admin import widgets class CustomModelAdmin: def formfield_for_manytomany(self, db_field, request=None, **kwargs): """ Get a form Field for a ManyToManyField. """
Note (August 27, 2019):
I am fully aware of how inheritance / inheritance works and what is best suited to solve such problems. However, as I have repeated in the comments below, subclasses will not solve the OP problem as indicated , i.e. doing filter_horizontal or filter_vertical by default . With the help of subclasses, you will need to not only register your subclass for all your models, but also unregister each subclass of ModelAdmin that is registered in the built-in Django applications and third-party applications that you installed, and then register new subclasses of ModelAdmin. So, for example, for the Django built-in custom model ...
admin.site.unregister(User) class CustomModelAdmin(admin.ModelAdmin): """ Add your changes here """ admin.site.register(User, CustomModelAdmin)
... then repeat the same code for all Django applications and third-party applications that you have installed. I do not think that this is what the OP wanted, hence my answer.
source share