在Django管理界面中只读模型? [英] Readonly models in Django admin interface?
问题描述
如何在管理界面中使模型完全只读?这是一种日志表,我使用管理功能进行搜索,排序,过滤等功能,但无需修改日志。
这个例子看起来像一个重复的,这里是不是我想要做的:
- 我不是寻找只读字段(即使使每个字段只读仍然可以让您创建新记录)
- 我不是想创建一个只读用户:每个用户都应该是只读的。
只是观看(你不会找到视图权限)。为了达到你想要的目的,你必须禁止添加,删除和使所有字段只读:
class MyAdmin
def has_add_permission(self,request,obj = None):
return False
def has_delete_permission(self,request,obj = None):
return False
(如果您禁止更改,甚至不会看到对象)
对于一些未经测试的代码,尝试自动设置所有字段为只读请参阅我的答案整个模型为只读
编辑:还未经过测试,但只是看看我的LogEntryAdmin和它有
readonly_fields = MyModel._meta.get_all_field_names()
/ pre>
不知道是否可以在所有情况下工作。
编辑:QuerySet.delete( )可能会批量删除对象。要解决这个问题,请提供您自己的对象管理器和相应的QuerySet子类,不会删除 - 请参阅在Django中覆盖QuerySet.delete()
How can I make a model completely read-only in the admin interface? It's for a kind of log table, where I'm using the admin features to search, sort, filter etc, but there is no need to modify the log.
In case this looks like a duplicate, here's not what I'm trying to do:
- I'm not looking for readonly fields (even making every field readonly would still let you create new records)
- I'm not looking to create a readonly user: every user should be readonly.
The admin is for editing, not just viewing (you won't find a "view" permission). In order to achieve what you want you'll have to forbid adding, deleting, and make all fields readonly:
class MyAdmin(ModelAdmin):
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
(if you forbid changing you won't even get to see the objects)
For some untested code that tries to automate setting all fields read-only see my answer to Whole model as read-only
EDIT: also untested but just had a look at my LogEntryAdmin and it has
readonly_fields = MyModel._meta.get_all_field_names()
Don't know if that will work in all cases.
EDIT: QuerySet.delete() may still bulk delete objects. To get around this, provide your own "objects" manager and corresponding QuerySet subclass which doesn't delete - see Overriding QuerySet.delete() in Django
这篇关于在Django管理界面中只读模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!