我想授予某些用户创建文章的权限,而无需为其分配员工状态。
原因是我不希望任何用户访问管理面板进行身份验证,就像将@staff_member_required
添加到视图时一样。相反,我只想在拥有此类权限的用户的个人资料中添加/add/article
链接。
我怎样才能做到这一点?
答案 0 :(得分:2)
如果您使用的是传统功能视图,则可以执行以下操作:
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
中)或使用django-braces中的PermissionRequiredMixin
({{3} }) - 或者只是在CBV的dispatch()
方法中进行自己的检查。
此外,在您的模板中,将您的add_article网址放入perms检查中,如下所示:
{% if perms.articles.add_article %} Show url for article editing only to users that have the rpmission {% endif %}