Search code examples
pythondjangodjango-admin

django admin inlines: get object from formfield_for_foreignkey


I am trying to filter the options shown in a foreignkey field, within a django admin inline. Thus, I want to access the parent object being edited. I have been researching but couldn't find any solution.

class ProjectGroupMembershipInline(admin.StackedInline):
    model = ProjectGroupMembership
    extra = 1
    formset = ProjectGroupMembershipInlineFormSet
    form = ProjectGroupMembershipInlineForm

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field.name == 'group':
            kwargs['queryset'] = Group.objects.filter(some_filtering_here=object_being_edited)
        return super(ProjectGroupMembershipInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

I have verified that kwargs is empty when editing an object, so I can't get the object from there.

Any help please? Thanks


Solution

  • To filter the choices available for a foreign key field in an admin inline, I override the form so that I can update the form field's queryset attribute. That way you have access to self.instance which is the object being edited in the form. So something like this:

    class ProjectGroupMembershipInlineForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['group'].queryset = Group.objects.filter(
                some_filtering_here=self.instance
            )
            
    

    You don't need to use formfield_for_foreignkey if you do the above and it should accomplish what you described.