You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用django-reverse-admin时如何完全禁用内联对象的删除功能?

问题描述

使用django-reverse-admin开发后端管理页面时,初始ComputerAdmin代码如下:

class ComputerAdmin(ReverseModelAdmin):
    list_display = ('employee', 'ip', 'mac', 'name', 'hardware')
    list_filter = ('employee__branch', )
    inline_type = 'tabular'
    inline_reverse = ['hardware', ]
    show_full_result_count = False

由于外键约束仅允许关联一个元素,需要移除内联区域的删除列、删除图标。查阅官方文档未找到仅针对内联生效的删除权限配置方法,后续新增了HardwareInline类,重写has_delete_permission返回False,同时在ComputerAdmin的inline_reverse中指定对应admin_class,调整后代码如下:

class HardwareInline(admin.TabularInline):
    model = Hardware
    def has_delete_permission(self, request, obj=None):
        return False

class EmployeeAdmin(admin.ModelAdmin):
    list_display = ('group', 'branch', 'name')
    list_filter = ('group', )

class ComputerAdmin(ReverseModelAdmin):
    list_display = ('employee', 'ip', 'mac', 'name', 'hardware')
    list_filter = ('employee__group', 'employee__branch', )
    inline_type = 'tabular'
    inline_reverse = [ { 'field_name': 'hardware', 'admin_class': HardwareInline } ]

调整后内联区域的删除列已经消失,但内联区域下方仍显示删除按钮,需要彻底禁用内联对象的删除功能。

解决方案

你只需要在自定义的Inline类中新增can_delete = False属性即可,这是Django原生内联类的配置项,优先级高于权限判断方法,会直接屏蔽所有删除相关UI,包括底部的删除按钮。如果要同时兼顾逻辑层权限校验,可以保留has_delete_permission的重写,修改后的完整代码如下:

class HardwareInline(admin.TabularInline):
    model = Hardware
    can_delete = False  # 直接禁用所有删除相关UI渲染

    def has_delete_permission(self, request, obj=None):
        return False
    
    # 如果添加上面配置后底部仍有删除按钮,补充重写get_formset方法强制禁用删除
    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        formset.can_delete = False
        return formset

class EmployeeAdmin(admin.ModelAdmin):
    list_display = ('group', 'branch', 'name')
    list_filter = ('group', )

class ComputerAdmin(ReverseModelAdmin):
    list_display = ('employee', 'ip', 'mac', 'name', 'hardware')
    list_filter = ('employee__group', 'employee__branch', )
    inline_type = 'tabular'
    inline_reverse = [ { 'field_name': 'hardware', 'admin_class': HardwareInline } ]

配置后会从UI层和逻辑层两层同时禁用内联对象的删除能力,完全符合一对一外键的约束要求。

内容的提问来源于stack exchange,提问作者Amine Messaoudi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:06:03