【问题标题】:Django username not displaying at allDjango用户名根本不显示
【发布时间】:2013-11-16 21:49:26
【问题描述】:

我是 Django 的绝对初学者。我已按照本教程进行操作: http://www.rdegges.com/user-authentication-with-django/

经过一些更改后,它设法让它在新版本上运行。 只有一个问题。登录后提示:

<h2>Welcome, {{ user.username }}</h2>

应该显示当前登录用户的用户名。 即使一切正常,并且我正在登录并转移到这个网站,它只是说:“你好,”并且在 {{ user.username }} 的位置没有生成任何内容。有人知道我可能会错过什么吗?

【问题讨论】:

  • 你在项目的setting.py中的TEMPLATE_CONTEXT_PROCESSORS中有“django.core.context_processors.auth”吗?
  • 我添加了 django.contrib.auth.context_processors.auth 因为你建议的应该适用于 1.2 及更低版本。无论如何,它仍然没有解决我的问题。
  • 尝试在 MIDDLEWARE_CLASSES 中启用'django.contrib.sessions.middleware.SessionMiddleware',但记得放在'django.contrib.auth.middleware.AuthenticationMiddleware'之前
  • 很遗憾,默认是这样的。
  • 你确定你已经登录了吗?只用 {{ user }} 试试看会发生什么

标签: python django django-templates django-authentication


【解决方案1】:

我解决了你的问题,问题是关于render_to_responsedjango.template.RequestContext 文件uploader/main/views.py 应该是这样的:

from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
rom django.template import RequestContext

@login_required
def main_main_page(request):
    return render_to_response('main/index.html', context_instance=RequestContext(request))

【讨论】:

  • 还有一个建议:统一缩进,即用四个空格替换 tab 字符
  • 感谢您的提示和解决我的问题。有用! :)
【解决方案2】:

编辑:只要您在项目设置中的 TEMPLATE_CONTEXT_PROCESSORS 中有“django.core.context_processors.auth”,您就不需要添加请求以在模板中引用经过身份验证的用户。

您的核心问题是通过@juliocesar 在他的回答中描述的 context_instance 将请求传递给模板。

原答案:

试试

<h2>Welcome, {{ request.user.username }}</h2>

本教程中的视图似乎没有定义“用户”变量并将其返回给模板,但您可以在请求中访问经过身份验证的用户信息。

【讨论】:

  • 无论如何,您能指导我如何为用户创建模板吗?请求不起作用,但也许那样可以..?
  • -1 @lightstrike“似乎没有定义'user'变量并将其返回到模板中”没有必要在模板中显示user,只需将django.core.context_processors.auth添加为@ AlexParakhnevich 回答问题
  • @juliocesar 你完全正确,我的错。这段时间我一直在使用 request.user...
  • @Fengson - juliocesar 为您解决了问题,我能够确认可以解决您的问题。在您确认它对您有用后,请务必接受他的回答! :-)
猜你喜欢
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 2013-06-05
  • 2023-03-08
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多