我是作者django-cancan
图书馆https://github.com/pgorecki/django-cancan https://github.com/pgorecki/django-cancan它致力于解决您所描述的确切问题。
其原理如下:首先,确定每个用户的能力,然后在视图中,您可以检查给定对象、模型的用户能力,或者可以根据这些能力检索查询集。
声明部分如下所示:
def declare_abilities(user, ability):
if not user.is_authenticated:
# Allow anonymous users to view only published articles
ability.can('view', Article, published=True)
else:
# logged in user can view any article...
ability.can('view', Article)
# ... and change his own
ability.can('change', Article, author=user)
# ... and add new ones
ability.can('add', Article)
if user.is_superuser:
# Allow superuser to view and change any article
ability.can('view', Article)
ability.can('change', Article)
然后您可以检查每个对象级别的能力:
def article_detail_view(request, pk):
article = Article.objects.get(pk=pk)
if request.ability.can('view', article):
...
或在模型级别:
def article_create_view(request, pk):
if request.ability.can('add', Article):
...
或获取具有可访问对象的查询集:
def another_list_view(request, pk):
articles = request.ability.queryset_for('view', Article)
...