cuốn sách gpt4 ai đã làm

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

In lại Tác giả: Walker 123 更新时间:2023-11-28 19:35:05 32 4
mua khóa gpt4 Nike

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

例如,如果我只想:

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

我正在使用 django-registration/authentication

câu trả lời hay nhất

当前 Django 版本的替代方法:

{% if user.is_authenticated %}

Welcome, {{ user.get_username }}. Thanks for logging in.


{% else %}

Welcome, new user. Please log in.


{% endif %}


Để ý:

  • 在 View 中使用 request.user.get_username() 并在模板中使用 user.get_username。优先于直接引用 username tài sản. Source
  • 如果使用 RequestContext,则此模板上下文变量可用。
  • django.contrib.auth.context_processors.auth 默认启用并包含变量 user
  • 您不需要启用 django.core.context_processors.request 模板上下文处理器。

nguồn: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
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress