Django Admin - 禁用特定模型实例的编辑链接

时间:2018-05-28 07:58:42

标签: django python-3.x django-admin

我定义了以下模型:

class BankAccountAdmin(admin.ModelAdmin):
    list_display = ('iban', 'owner',)

    def has_change_permission(self, request, obj=None):
        return obj is None or obj.owner == request.user

admin.py上的以下ModelAdmin:

reduce

到目前为止,django admin只允许用户编辑他们的银行帐户,当用户没有更改权限时返回403 Forbidden错误。

问题是仍然显示所有BankAccount实例的链接。

有关如何在BankAccount管理视图中禁用这些特定实例的链接的想法吗?

1 个答案:

答案 0 :(得分:0)

我终于在admin.py上实现了解决方法,如下所示。评论解释了添加的行。

from django.utils.html import format_html

class BankAccountAdmin(admin.ModelAdmin):
    list_display = ('iban_link', 'owner',)
    list_display_links = None  # The field displaying the link is given by iban_link()

    editable_objs = []  # This variable will store the instances that the logged in user can edit

    def has_change_permission(self, request, obj=None):
        return obj is None or obj.owner == request.user

    def iban_link(self, obj):
        # Shows the link only if obj is editable by the user. 
        if obj in self.editable_objs:
            return format_html("<a href='{id}'>{iban}</a>",
                               id=obj.id, iban=obj.iban,
                               )
        else:
            return format_html("{iban}",
                               id=obj.id, iban=obj.iban,
                               )

    # We make use of get_queryset method to fetch request.user and store the editable instances
    def get_queryset(self, request):
        # Stores all the BankAccount instances that the logged in user is owner of
        self.editable_objs = BankAccount.objects.filter(owner=request.user)
        return super(UserAdmin, self).get_queryset(request)

请注意,如果没有行list_display_links = None,仍会显示所有实例的链接。这是因为默认行为显示第一列上所有实例的链接。