gpt4 book ai didi

django - Django:从内联模型管理员访问父实例

转载 作者:行者123 更新时间:2023-12-03 21:17:46 27 4
gpt4 key购买 nike

如何从内联模型管理员访问父实例?

我的目标是根据父实例的状态覆盖has_add_permission函数。如果父级的状态不同于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,]

最佳答案

Django <2.0答案:

使用Django的Request对象(您可以访问)检索request.path_info,然后从resolve匹配项中的参数中检索PK。例:

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]


Django> = 2.0答案:

归功于 Mark Chackerian进行以下更新:

使用Django的Request对象(您可以访问)检索 request.path_info,然后从 resolve匹配项中的参数中检索PK。例:

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]

关于django - Django:从内联模型管理员访问父实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32150088/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com