Django admin - 使所有字段只读

2022-01-25 00:00:00 python django django-admin

问题描述

我正在尝试将所有字段设为只读而不明确列出它们.

I'm trying to make all fields readonly without listing them explicitly.

类似:

class CustomAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return self.readonly_fields

        return self.fields

问题是CustomAdmin.fields此时没有设置.

有什么想法吗?


解决方案

注意,self.model._meta.fields 不一定是 CustomAdmin 的同一个字段!

Careful, self.model._meta.fields are not necessarily the same fields that CustomAdmin has!

Admin 的所有字段"看起来更像这样:

"All fields of the Admin" would look more like this:

from django.contrib import admin
from django.contrib.admin.utils import flatten_fieldsets

class CustomAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return self.readonly_fields

        if self.declared_fieldsets:
            return flatten_fieldsets(self.declared_fieldsets)
        else:
            return list(set(
                [field.name for field in self.opts.local_fields] +
                [field.name for field in self.opts.local_many_to_many]
            ))

相关文章