Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter_horizontal filtering

I have 2 models related by M2M type of relationship. I use filter_horizontal in the admin for editing my entities.

However, I would like to have a control on what is presented in the left side of the filter_horizontal widget. For example, I would like to filter and show only those entities that match some certain criteria.

like image 781
Michael Kalika Avatar asked Oct 18 '25 15:10

Michael Kalika


1 Answers

I think I found it!

class MyModelAdmin(admin.ModelAdmin):
def formfield_for_manytomany(self, db_field, request, **kwargs):
    if db_field.name == "cars":
        kwargs["queryset"] = Car.objects.filter(owner=request.user)
    return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

ModelAdmin.formfield_for_manytomany(db_field, request, **kwargs)

like image 60
Michael Kalika Avatar answered Oct 20 '25 07:10

Michael Kalika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!