Anthony Roberts
Anthony Roberts

Reputation: 2021

Django-Admin override default formfield for a foreign keys field

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)?

Upvotes: 1

Views: 898

Answers (1)

Anthony Roberts
Anthony Roberts

Reputation: 2021

So I am answering my own question here.

def formfield_for_foreignkey(self, db_field, request, **kwargs):
   if db_field.name == "sub_type":
       subtype = Product.objects.all()
       if not request.user.is_superuser:
           kwargs["queryset"] = subtype.filter(publisher=request.user)
       else:
           kwargs["queryset"] = subtype
   return super(SimpleSubscriberAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

I needed to change

kwargs["queryset"] = SimpleSubscriber.objects.filter(sub_type=request.user)

to this:

subtype = Product.objects.all()
    if not request.user.is_superuser:
        kwargs["queryset"] = subtype.filter(publisher=request.user)
    else:
        kwargs["queryset"] = subtype

I'm learning the hard way about filtering ForeignKey objects. Hope this saves someone a headache.

Upvotes: 1

Related Questions