【发布时间】:2012-11-22 16:18:21
【问题描述】:
从 django 模板获取用户信息的最佳方式是什么?
例如,如果我只想:
- 如果用户已登录,则显示“欢迎 [用户名]”
- 否则,显示登录按钮。
我正在使用 django-registration/authentication
【问题讨论】:
标签: django django-authentication django-registration
从 django 模板获取用户信息的最佳方式是什么?
例如,如果我只想:
我正在使用 django-registration/authentication
【问题讨论】:
标签: django django-authentication django-registration
当前 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 %}
注意:
request.user.get_username(),在模板中使用user.get_username。优先于直接引用username 属性。 Source
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
【讨论】:
{% if request.user.is_authenticated %}Welcome '{{ request.user.username }}'
{% else %}<a href="{% url django.contrib.auth.login %}">Login</a>{% endif %}
并确保您的settings.py 中安装了request 模板上下文处理器:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request',
...
)
【讨论】:
根据问题标题,以下内容可能对某人有用。在我的模板中使用了以下内容:
用户名:{{ user.username }}
用户全名:{{ user.get_full_name }}
用户组:{{ user.groups.all.0 }}
电子邮件:{{ user.email }}
会话开始于:{{ user.last_login }}
谢谢:)
【讨论】:
首先,首先,如果您的字段更改了名称,您必须以这种方式覆盖函数(get_full_name()、get_short_name() 等):
def get_full_name(self):
return self.names + ' ' + self.lastnames
def get_short_name(self):
return self.names
在模板中,可以这样显示
{% if user.is_authenticated %}
<strong>{{ user.get_short_name }}</strong>
{% endif %}
这些是认证https://docs.djangoproject.com/es/2.1/topics/auth/customizing/中的方法
【讨论】:
以下是一个完整的工作解决方案,还考虑了翻译:
template.html:
{% blocktrans %}Welcome {{ USER_NAME }}!{% endblocktrans %}
context_processors.py:
def template_constants(request):
return {
'USER_NAME': '' if request.user.is_anonymous else request.user.first_name,
# other values here...
}
提醒在settings.py 中正确设置您的自定义上下文处理器:
TEMPLATES = [
{
# ...
'OPTIONS': {
'context_processors': [
# ...
'your_app.context_processors.template_constants',
],
},
},
]
这就是你在django.po 中得到的:
#: templates/home.html:11
#, python-format
msgid "Hi %(USER_NAME)s!"
msgstr "..."
一个好的做法是将逻辑保留在模板之外:为此,您可以轻松自定义直接在context_processors.py 中显示的用户名。
【讨论】: