gpt4 book ai didi

django - 在django模板中获取用户信息

转载 作者:行者123 更新时间:2023-11-28 19:35:05 32 4
gpt4 key购买 nike

从 django 模板获取用户信息的最佳方式是什么?

例如,如果我只想:

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

我正在使用 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 %}


注意:

  • 在 View 中使用 request.user.get_username() 并在模板中使用 user.get_username。优先于直接引用 username 属性。 Source
  • 如果使用 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

关于django - 在django模板中获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13713077/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com