How can I access the parent instance from the inline model admin?
My goal is to override the has_add_permission
function based on the status of the parent instance. I don't want to allow to add a child if the status of the parent is different than 1.
class ChildInline(admin.TabularInline):
model = Child
form = ChildForm
fields = (
...
)
extra = 0
def has_add_permission(self, request):
# Return True only if the parent has status == 1
# How to get to the parent instance?
#return True
class ParentAdmin(admin.ModelAdmin):
inlines = [ChildInline,]
Use Django's Request object (which you have access to) to retrieve the request.path_info
, then retrieve the PK from the args in the resolve
match. Example:
from django.contrib import admin
from django.core.urlresolvers import resolve
from app.models import YourParentModel, YourInlineModel
class YourInlineModelInline(admin.StackedInline):
model = YourInlineModel
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
def has_add_permission(self, request):
parent = self.get_parent_object_from_request(request)
# Validate that the parent status is active (1)
if parent:
return parent.status == 1
# No parent - return original has_add_permission() check
return super(YourInlineModelInline, self).has_add_permission(request)
@admin.register(YourParentModel)
class YourParentModelAdmin(admin.ModelAdmin):
inlines = [YourInlineModelInline]
Credit to Mark Chackerian for the below update:
Use Django's Request object (which you have access to) to retrieve the request.path_info
, then retrieve the PK from the args in the resolve
match. Example:
from django.contrib import admin
from django.urls import resolve
from app.models import YourParentModel, YourInlineModel
class YourInlineModelInline(admin.StackedInline):
model = YourInlineModel
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
def has_add_permission(self, request):
parent = self.get_parent_object_from_request(request)
# Validate that the parent status is active (1)
if parent:
return parent.status == 1
# No parent - return original has_add_permission() check
return super(YourInlineModelInline, self).has_add_permission(request)
@admin.register(YourParentModel)
class YourParentModelAdmin(admin.ModelAdmin):
inlines = [YourInlineModelInline]
I think this is a cleaner way to get the parent instance in the inline model.
class ChildInline(admin.TabularInline):
model = Child
form = ChildForm
fields = (...)
extra = 0
def get_formset(self, request, obj=None, **kwargs):
self.parent_obj = obj
return super(ChildInline, self).get_formset(request, obj, **kwargs)
def has_add_permission(self, request):
# Return True only if the parent has status == 1
return self.parent_obj.status == 1
class ParentAdmin(admin.ModelAdmin):
inlines = [ChildInline, ]
I tried the solution of Michael B but didn't work for me, I had to use this instead (a small modification that uses kwargs):
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
BaseInlineFormSet has the attribute self.instance
which is the reference to the parent object.
In the constructor, the queryset is intialized and filtered using this instance. If you need adjustments, you can change the queryset argument to the constructor or use inlineformset_factory
to set the formset up according to your needs.
class BaseInlineFormSet(BaseModelFormSet):
"""A formset for child objects related to a parent."""
def __init__(self, data=None, files=None, instance=None,
save_as_new=False, prefix=None, queryset=None, **kwargs):
if instance is None:
self.instance = self.fk.remote_field.model()
else:
self.instance = instance
self.save_as_new = save_as_new
if queryset is None:
queryset = self.model._default_manager
if self.instance.pk is not None:
qs = queryset.filter(**{self.fk.name: self.instance})
else:
qs = queryset.none()
self.unique_fields = {self.fk.name}
super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
see https://docs.djangoproject.com/en/3.2/_modules/django/forms/models/
If you extends from this, make sure to run super().__init__()
before accessing self.instance
.
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