从 django 模板获取用户信息的最佳方法是什么?
例如,如果我只想:
- 如果用户已登录,则显示“欢迎[用户名]”
- 否则,显示登录按钮。
我正在使用 django 注册/身份验证
当前 Django 版本的替代方法:
{% if user.is_authenticated %}
<p>Welcome, {{ user.get_username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
Note:
- Use
request.user.get_username()
在视图&user.get_username
在模板中。优先于推荐username
直接属性。Source https://docs.djangoproject.com/en/dev/ref/contrib/auth/#django.contrib.auth.models.User.get_username
- 如果使用 RequestContext,则此模板上下文变量可用。
-
django.contrib.auth.context_processors.auth
默认启用并包含变量 user
- 您不需要启用
django.core.context_processors.request
模板上下文处理器。
来源 :https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)