问题描述
我想类似的问题会在这里讨论,但我找不到.
I suppose similar problem would have been discussed here, but I couldn't find it.
假设我有一个编辑和一个主管.我希望编辑能够添加新内容(例如新闻帖子),但在发布之前必须得到主管的认可.
Let's suppose I have an Editor and a Supervisor. I want the Editor to be able to add new content (eg. a news post) but before publication it has to be acknowledged by Supervisor.
当编辑器列出所有项目时,我想将模型上的某些字段(例如确认"字段)设置为只读(这样他就可以知道什么已经确认以及什么仍在等待批准)但是主管应该能够改变一切(list_editable 将是完美)
When Editor lists all items, I want to set some fields on the models (like an 'ack' field) as read-only (so he could know what had been ack'ed and what's still waiting approval) but the Supervisor should be able to change everything (list_editable would be perfect)
这个问题有哪些可能的解决方案?
What are the possible solutions to this problem?
推荐答案
我认为有一个更简单的方法来做到这一点:
I think there is a more easy way to do that:
请客,我们也有同样的Blog-Post问题
Guest we have the same problem of Blog-Post
博客/models.py:
blog/models.py:
Class Blog(models.Model):
...
#fields like autor, title, stuff..
...
class Post(models.Model):
...
#fields like blog, title, stuff..
...
approved = models.BooleanField(default=False)
approved_by = models.ForeignKey(User)
class Meta:
permissions = (
("can_approve_post", "Can approve post"),
)
魔法就在管理中:
博客/admin.py:
blog/admin.py:
...
from django.views.decorators.csrf import csrf_protect
...
def has_approval_permission(request, obj=None):
if request.user.has_perm('blog.can_approve_post'):
return True
return False
Class PostAdmin(admin.ModelAdmin):
@csrf_protect
def changelist_view(self, request, extra_context=None):
if not has_approval_permission(request):
self.list_display = [...] # list of fields to show if user can't approve the post
self.editable = [...]
else:
self.list_display = [...] # list of fields to show if user can approve the post
return super(PostAdmin, self).changelist_view(request, extra_context)
def get_form(self, request, obj=None, **kwargs):
if not has_approval_permission(request, obj):
self.fields = [...] # same thing
else:
self.fields = ['approved']
return super(PostAdmin, self).get_form(request, obj, **kwargs)
这样就可以使用自定义权限的api在 django 中,如果需要,您可以覆盖保存模型或获取查询集的方法.在 has_approval_permission
方法中,您可以定义用户何时可以或不能做某事的逻辑.
In this way you can use the api of custom permission in django, and you can override the methods for save the model or get the queryset if you have to. In the methid has_approval_permission
you can define the logic of when the user can or can't to do something.
这篇关于如何根据用户限制 django-admin 中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2