注意
从技术上来说,只有当你使用了 requestcontext这些变量才可用。 并且template_context_processors 设置包含了 “django.core.context_processors.auth” (默认情况就是如此)时,这些变量才能在模板context中使用。 template_context_processors 设置包含了 django.core.context_processors.auth (默认情况就是如此)时,这些变量才能在模板context中使用。
当使用 requestcontext 时, 当前用户 (是一个 user 实例或一个 anonymoususer 实例) 存储在模板变量 {{ user }} 中:
{% if user.is_authenticated %} welcome, {{ user.username }}. thanks for logging in.
{% else %} welcome, new user. please log in.
{% endif %}
这些用户的权限信息存储在 {{ perms }} 模板变量中。
你有两种方式来使用 perms 对象。 你可以使用类似于 {{ perms.polls }} 的形式来检查,对于某个特定的应用,一个用户是否具有 任意 权限;你也可以使用 {{ perms.polls.can_vote }} 这样的形式,来检查一个用户是否拥有特定的权限。
这样你就可以在模板中的 {% if %} 语句中检查权限:
{% if perms.polls %} you have permission to do something in the polls app.
{% if perms.polls.can_vote %} you can vote!
{% endif %}{% else %} you don't have permission to do anything in the polls app.
{% endif %}
