django admin - 组编辑或查看模型的权限 [英] django admin - group permissions to edit or view models
问题描述
我正在寻找一种方法来自定义Django管理,以支持基于用户组的权限。
I'm searching for a way to customize the Django Administration to support permissions based on the user group.
例如,我刚刚创建了Developers组,现在我也创建了门票模型,用AdminModel来指定如何列出数据。
For example, I've just created the Developers group, now I've also created the Tickets model, with AdminModel to specify how to list data.
我想让这个模型只有开发人员可以看到,而且隐藏彼此不在此组中(例如,根据组过滤视图)。
我已经阅读了很多文档,但是找不到并理解如何使用它。
I'd like to have this model visible only by Developers, and hidden to each other not in this group (eg filter the view based on groups). I've read a lot of documentations, but couldn't really find and understand what to do to have it working.
为了安全起见,我会还需要在运行时检查用户组,为特定模型(对于开发人员组之外的人员隐藏的对象)添加删除对象,否则只需要知道使用该模型的URL:s
For security purposes I'd also need to check user groups at runtime when adding-deleting objects for a specific model (the one I've hidden to people outside the Developers group), otherwise it would only need to know the URL to use the model :s
它看起来像一个简单的任务,但也许我错过了任何第三方中间件,或只是一种方法?如果需要,我也准备编辑管理视图,但是我需要知道该做什么。
It looks like a simple task, but maybe I'm missing something... any 3rd party middleware, or just a way to do it? I'm also ready to edit the administration views if needed, but I need to know what do to.
谢谢: - )
推荐答案
ModelAdmin
有三种处理用户权限的方法: has_add_permission
, has_change_permission
和 has_delete_permission
。所有三个应该返回布尔值( True
/ False
)。
ModelAdmin
has three methods dealing with user permission: has_add_permission
, has_change_permission
and has_delete_permission
. All three should return boolean (True
/False
).
所以你可以这样做:
class TicketAdmin(admin.ModelAdmin):
...
def has_add_permission(self, request):
return request.user.groups.filter(name='Developers').exists()
def has_change_permission(self, request, obj=None):
return request.user.groups.filter(name='Developers').exists()
def has_delete_permission(self, request, obj=None):
return request.user.groups.filter(name='Developers').exists()
当 False
从其中一个返回,结果是403 Forbidden。
When False
is returned from one of these, it's results in a 403 Forbidden.
这篇关于django admin - 组编辑或查看模型的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!