在Django模板中获取用户信息

70

如何从Django模板中获取用户信息是最好的方法?

例如,如果我只想:

  1. 如果用户已登录,则显示“欢迎[用户名]”
  2. 否则,显示登录按钮。

我正在使用django-registration/authentication。


1
可能是如何在Django模板中访问用户配置文件?的重复问题。 - Ciro Santilli OurBigBook.com
5个回答

133

当前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属性。这是推荐的方法。来源
  • 如果使用了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


46
{% 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',
    ...
)

40

根据问题标题,以下内容可能对某些人有用。 在我的模板中使用了以下内容:

用户名: {{ user.username }}

用户全名: {{ user.get_full_name }}

用户组: {{ user.groups.all.0 }}

电子邮件: {{ user.email }}

会话开始时间: {{ user.last_login }}

谢谢 :)


我本来也想使用{{ user.username }},但正如@user在被接受的答案中提到的那样,它有一些缺点,应该使用用户实例来优先选择{{ user.get_username }}。 - Advena

2

首先,如果您的字段更改了名称,您必须覆盖函数(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/


0
以下是一个完整的工作解决方案,还考虑了翻译问题:

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中直接自定义显示的用户名。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接