您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在Django的模板中使用认证数据的方法

2024/4/27 10:35:45发布23次查看
当前登入的用户以及他(她)的权限可以通过 requestcontext 在模板的context中使用。
注意
从技术上来说,只有当你使用了 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 %}
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product