Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Created October 6, 2017 10:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LowerDeez/8697604c3f4378a1ca92a53a4d12016f to your computer and use it in GitHub Desktop.
Save LowerDeez/8697604c3f4378a1ca92a53a4d12016f to your computer and use it in GitHub Desktop.
Django. Admin Tabular Inline. Get parent object
class ProductVariantAdminInline(admin.TabularInline):
extra = 0
model = ProductVariant
def get_parent_object_from_request(self, request):
"""
Returns the parent object from the request or None.
Note that this only works for Inlines, because the `parent_model`
is not available in the regular admin.ModelAdmin as an attribute.
"""
resolved = resolve(request.path_info)
if resolved.args:
return self.parent_model.objects.get(pk=resolved.args[0])
return None
@midir99
Copy link

midir99 commented Apr 14, 2021

This did't work for me, I had to change it to the following:

def get_parent_object_from_request(self, request):
        """
        Returns the parent object from the request or None.

        Note that this only works for Inlines, because the `parent_model`
        is not available in the regular admin.ModelAdmin as an attribute.
        """
        resolved = resolve(request.path_info)
        if resolved.kwargs:
            return self.parent_model.objects.get(pk=resolved.kwargs["object_id"])
        return None

@josemarimanio
Copy link

This did't work for me, I had to change it to the following:

def get_parent_object_from_request(self, request):
        """
        Returns the parent object from the request or None.

        Note that this only works for Inlines, because the `parent_model`
        is not available in the regular admin.ModelAdmin as an attribute.
        """
        resolved = resolve(request.path_info)
        if resolved.kwargs:
            return self.parent_model.objects.get(pk=resolved.kwargs["object_id"])
        return None

This resolved the issue that's bugging me for hours. Thanks! 🍻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment