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

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

问题描述

有没有办法在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所做的所有字段,而不用直接使用readonly字段进行递归:

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子类/ mixin此管理员应该是只读管理员。

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

PS:在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...

编辑:关于设置所有字段readonly,也未经测试但看起来很有希望:

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天全站免登陆