整个模型为只读 [英] Whole model as read-only

查看:22
本文介绍了整个模型为只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 django 管理中使模型只读?但我的意思是整个模型.所以,不添加,不删除,不改变,只看到对象和字段,一切都是只读的?

Is there a way to make a model read-only in the django admin? but I mean the whole model. So, no adding, no deleting, no changing, just see the objects and the fields, everything as read-only?

推荐答案

ModelAdmin 提供了钩子 get_readonly_fields() - 以下未经测试,我的想法是按照 ModelAdmin 的方式确定所有字段,而不会遇到递归只读字段本身:

ModelAdmin provides the hook get_readonly_fields() - the following is untested, my idea being to determine all fields the way ModelAdmin does it, without running into a recursion with the readonly fields themselves:

from django.contrib.admin.util import flatten_fieldsets

class ReadOnlyAdmin(ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if self.declared_fieldsets:
            fields = flatten_fieldsets(self.declared_fieldsets)
        else:
            form = self.get_formset(request, obj).form
            fields = form.base_fields.keys()
        return fields

然后在该管理员应该是只读管理员的任何地方将其子类化/混合.

then subclass/mixin this admin whereever it should be a read-only admin.

对于添加/删除,以及让他们的按钮消失,你可能还想添加

For add/delete, and to make their buttons disappear, you'll probably also want to add

    def has_add_permission(self, request):
        # Nobody is allowed to add
        return False
    def has_delete_permission(self, request, obj=None):
        # Nobody is allowed to delete
        return False

P.S.:在 ModelAdmin 中,如果 has_change_permission(查找或覆盖)返回 False,您将无法进入对象的更改视图 - 甚至不会显示指向它的链接.如果这样做的话实际上会很酷,并且默认的 get_readonly_fields() 检查更改权限并将所有字段设置为只读,在这种情况下,如上所示.这样,非更改者至少可以浏览数据......鉴于当前的管理结构假定 view=edit,正如 jathanism 指出的那样,这可能需要在添加/更改/删除之上引入查看"权限...

P.S.: In ModelAdmin, if has_change_permission (lookup or your override) returns False, you don't get to the change view of an object - and the link to it won't even be shown. It would actually be cool if it did, and the default get_readonly_fields() checked the change permission and set all fields to readonly in that case, like above. That way non-changers could at least browse the data... given that the current admin structure assumes view=edit, as jathanism points out, this would probably require the introduction of a "view" permission on top of add/change/delete...

关于将所有字段设置为只读,也未经测试但看起来很有希望:

regarding setting all fields readonly, also untested but looking promising:

readonly_fields = MyModel._meta.get_all_field_names()

这是另一个

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]
    ))

这篇关于整个模型为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆