【问题标题】:Django Admin - disable edit link for specific model instancesDjango Admin - 禁用特定模型实例的编辑链接
【发布时间】:2018-05-28 07:58:41
【问题描述】:

我定义了以下模型:

class BankAccount(models.Model):
    iban = models.CharField(max_length=34)
    owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='owner')

以及 admin.py 上的以下 ModelAdmin:

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

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

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

知道如何在 BankAccount 管理视图中禁用这些特定实例的链接吗?

【问题讨论】:

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


    【解决方案1】:

    我终于在 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 行,所有实例的链接仍会显示。这是因为默认行为会在第一列显示所有实例的链接。

    【讨论】:

      猜你喜欢
      • 2012-01-16
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      相关资源
      最近更新 更多