Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin inlines: get object from formfield_for_foreignkey

Tags:

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

like image 484
sogeking Avatar asked Jan 24 '14 16:01

sogeking


1 Answers

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) 
like image 169
mkoistinen Avatar answered Sep 21 '22 15:09

mkoistinen