Limiting Admin Choices Using limit_choices_to

I would like to limit the selection for ForeignKey in the admin user interface using limit_choices_to; however, I would like to achieve this without changing the model, since the model is derived from a library that I do not control. What is the way to dynamically achieve this? Or can I use the field in the admin model to achieve this?

Thanks, --Eytan

+6
source share
1 answer

Django provides an admin hook to change the set of foreign key requests: formfield_for_foreignkey

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

Source: https://habr.com/ru/post/902075/


All Articles