2015-02-06 62 views
2

我想授予某些用户创建文章的权限,而不分配他们的工作人员状态。如何在没有员工身份的情况下在Django中定义权限?

原因是我不想让任何用户到达管理面板进行身份验证,就像在将视图添加到@staff_member_required时一样。相反,我只想将/add/article链接添加到拥有此权限的用户个人资料。

我该如何做到这一点?

回答

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中的PermissionRequiredMixinhttp://django-braces.readthedocs.org/en/latest/access.html#permissionrequiredmixin) - 或者只是自己动手ks在CBV的dispatch()方法中。

而且,在你的模板把你的add_article网址内烫发检查,像这样:

 
{% if perms.articles.add_article %} 
    Show url for article editing only to users that have the rpmission 
{% endif %} 
+0

我使用的过渡功能视图。很好的帮助。谢谢Serafeim。 – Jand 2015-02-06 12:54:44

相关问题