Django admin:inline模型:如何从has_deletepermission方法访问当前记录id


Django 2.2

admin.py,背景和问题基本上都内联在代码中:

class ProductAdmin(<SomeSuperAdmin>)
inlines = [
ProductCommentInline,
]
# blah-blah...
class ProductCommentAdmin(<SomeSuperAdmin>):
# blah-blah...
class ProductCommentInline(admin.TabularInline):  
model = ProductComment
# blah-blah...
#this is called for each record in my queryset of ProductComments,
# and depending on one field value I want it to return True or False
def has_delete_permission(self, request, obj=None):
#here I have obj.id which is id of Product, but not ProductComment
#here I need to get somehow current ProductComment record data
product_comment_record = <get_somehow_current_record_data >
return product_comment_record.<some_bool_field>

如何从内联模型的has_delete_permission方法访问当前ProductComment记录数据

我意识到我有完整的ProductComment查询集:

all_productcomments_records = self.get_queryset(request).filter(product_id=obj.id),

但我需要访问当前记录数据。我在selfrequest中没有找到任何内容

好吧,最后对我有用的是Benoit Blanchon在这篇文章中给出的(有些改编的(答案:Django Admin-如何防止删除一些内联。它让我可以访问index,这是我想要的变量。

from django.forms.models import BaseInlineFormSet
class ProductCommentInlineFormSet(BaseInlineFormSet):
# set "delete" checkbox to grayed out state for already deleted (is_active=False)
def add_fields(self, form, index):
super().add_fields(form, index)
form.fields['DELETE'].disabled = False
if index != None:
try:
if not self.get_queryset()[index].is_active:
form.fields['DELETE'].disabled = True
except:
pass
class ProductCommentInline(admin.TabularInline): 
model = ProductComment
formset = ProductCommentInlineFormSet

最新更新