Django admin - 防止在字段变为真后更改字段

Django admin - prevent changing a field after it has become true

我在 admin.py 中注册了一个模型:

class OrderAdmin(admin.ModelAdmin):
    list_display = ('org_name', 'address', 'total_cost', 'phone', 'data_time', 'is_called', 'is_payed')
    search_fields = ('org_name', 'phone')
    list_filter = ('data_time', 'total_cost', 'data_time')
    list_editable = ('is_called', 'is_payed')
    readonly_fields = ('data_time', 'user', 'total_cost')
    inlines = [OrderItemsAdmin, ]

我需要做类似的事情:

class OrderAdmin(admin.ModelAdmin):
    list_display = ('org_name', 'address', 'total_cost', 'phone', 'data_time', 'is_called', 'is_payed')
    search_fields = ('org_name', 'phone')
    list_filter = ('data_time', 'total_cost', 'data_time')
    list_editable = ('is_called', 'is_payed')
    readonly_fields = ('data_time', 'user', 'total_cost')
    inlines = [OrderItemsAdmin, ]

    if 'is_called' == True:
        readonly_fields.append('is_called')

我认为这是可能的,所以问题是如何做到这一点?

你可以利用ModelAdmin.get_readonly_fields()方法

试试这个

class OrderAdmin(admin.ModelAdmin):
    ...

    def get_readonly_fields(self, request, obj=None):
        readonly_fields = super(OrderAdmin, self).get_readonly_fields(request, obj)

        if obj.is_called:
            readonly_fields.append("is_called")
            return readonly_fields

        return readonly_fields