I’ve read the documentation and tried to implement an override of the default formfield to display only items that belong to the current user (Publisher) in my admin. I have a SimpleSubscriber model with an object named sub_type that’s a ForeignKey to the model Product. There is also a Publisher model, and both SimpleSubscriber and Product have ForeignKey objects called publisher. In my admin.py I have this:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "sub_type":
kwargs["queryset"] = SimpleSubscriber.objects.filter(sub_type=request.user)
return super(SimpleSubscriberAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
In the documentation, it originally had
kwargs["queryset"] = SimpleSubscriber.objects.filter(owner=request.user)
But I got “FieldError: Cannot resolve keyword ‘owner’ into field” so I replaced owner with sub_type, but that populated the list with subscribers. It should be a list of sub_types (Products).
How do I get this list to show only the sub_types (Products) that belong to the current user (Publisher)?
So I am answering my own question here.
I needed to change
to this:
I’m learning the hard way about filtering ForeignKey objects. Hope this saves someone a headache.