我想授予某些用户创建文章的权限,而不向他们分配员工身份。
原因是我不希望任何用户访问管理面板进行身份验证,就像将 @staff_member_required
添加到 View 时发生的情况一样。相反,我只想添加一个 /add/article
链接到具有此类权限的用户的个人资料。
我怎样才能实现这一目标?
最佳答案
如果您使用传统的功能 View ,您可以执行以下操作:
def add_article(request): if not request.user.has_perm('articles.add_article'): return HttpResponseForbidden() # Now only users that have the permission will reach this # so add your normal view handling
但是,我建议使用django.contrib.auth.decorators.permission_required
装饰器来代替上面的:
@permission_required('articles.add_article') def add_article(request): # your normal view handling
如果您使用 CBV,则应该装饰 CBV 的 as_view()
方法(在 urls.py
中)或使用 PermissionRequiredMixin
来自 django-braces ( http://django-braces.readthedocs.org/en/latest/access.html#permissionrequiredmixin ) - 或者只是在 CBV 的 dispatch()
方法中进行自己的检查。
此外,在模板中将 add_article url 放入权限检查中,如下所示:
{% if perms.articles.add_article %} Show url for article editing only to users that have the rpmission {% endif %}
关于django - 如何在没有员工身份的Django中定义权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28365424/