【问题标题】:Django admin: inline model: how to access current record id from has_delete_permission methodDjango admin:内联模型:如何从 has_delete_permission 方法访问当前记录 id
【发布时间】:2020-02-24 18:13:07
【问题描述】:

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 中找到任何内容

【问题讨论】:

  • @bhaskarc 不确定您的意思,我使用的是 TabularInline。该链接没有解决以某种方式标记内联查询集的特定记录的问题,只是解释了如何过滤它。我不想过滤掉任何东西,我想以不同的方式对待它们。几乎是 8 年前的事了。

标签: django model admin inline


【解决方案1】:

好的,最后对我有用的是Benoit Blanchon 在这篇文章中的(有些改编的)答案:Django Admin - how to prevent deletion of some of the inlines。它让我可以访问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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2012-04-19
    • 2011-08-19
    • 2017-09-15
    • 2018-10-11
    • 2018-08-17
    相关资源
    最近更新 更多