如何从Django模板中获取用户信息是最好的方法?
例如,如果我只想:
- 如果用户已登录,则显示“欢迎[用户名]”
- 否则,显示登录按钮。
我正在使用django-registration/authentication。
如何从Django模板中获取用户信息是最好的方法?
例如,如果我只想:
我正在使用django-registration/authentication。
当前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
属性。这是推荐的方法。来源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
中直接自定义显示的用户名。