django中如何在template和view中做用户相关权限的判断?


如题,有没有详细一点的教程。在view和template中判断权限,组信息等,然后按条件显示不同的内容。

谢谢

权限判断 组判断 开发 django

妹特思棒慰 9 years, 8 months ago

角色判断

  • is_staff: 是否系统工作人员
  • is_superuser: 是否超级用户
  • is_active: 是否有效用户
  • is_anonymous(): 是否匿名用户
  • is_authenticated(): 是否登录了
  • groups: 该用户所在的groups
  • user_permissions: 该用户的所有权限

用户权限

在template中,可以使用下面的代码:

{% if perms.app_label.can_do_something %}
<form here>
{% endif %}

在view中,可以使用:

user.has_perm('app.view_task')

或者使用decorator如下:

@permission_required('polls.can_vote')

你可以参考 官方文档

当前 登录用户的权限信息 存储在template变量 {{ perms }} 中

兵库北香菜 answered 9 years, 8 months ago

Your Answer