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
Another way, that, IMHO, feels cleaner than, but is similar to @erichonkanen's answer is something like this:
class ProjectGroupMembershipInline(admin.StackedInline): # irrelevant bits.... def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "group": try: parent_id = request.resolver_match.args[0] kwargs["queryset"] = Group.objects.filter(some_column=parent_id) except IndexError: pass return super().formfield_for_foreignkey(db_field, request, **kwargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With