Django 1.4 - {{ request.user.username}} 不在模板中呈现 [英] Django 1.4 - {{ request.user.username}} doesn't render in template
问题描述
在我看来,我可以打印 request.user.username,但是在模板中,{{request.user.username}} 没有出现.为方便起见,我从函数中删除了逻辑,并导入了 render_to_response &请求上下文.
In my view, I can print request.user.username, however in the template, {{request.user.username}} does not appear. To make this easy, I removed the logic from the function, and I am importing render_to_response & RequestContext.
from django.shortcuts import render_to_response
from django.template import RequestContext
@login_required
@csrf_protect
def form(request):
print request.user.username
data = {}
return render_to_response('form.html', data, context_instance=RequestContext(request))
我的猜测是我的 settings.py 有问题.
My guess is that I have problem with my settings.py.
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'src',
)
预先感谢您的帮助-
推荐答案
As 文档中提到,经过身份验证的用户对象存储在模板中的 user
变量中.提到的文档包括以下示例:
As mentioned in the documentation, authenticated user's object is stored within user
variable in templates. Mentioned documentation includes the following example:
渲染模板 RequestContext
时,当前登录的用户(User
实例或 AnonymousUser
实例)存储在模板变量 {{ user }}
:
When rendering a template
RequestContext
, the currently logged-in user, either aUser
instance or anAnonymousUser
instance, is stored in the template variable{{ user }}
:
{% if user.is_authenticated %}
<p>Welcome, {{ user.get_username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
感谢@buffer 挖掘出这个旧答案,我已经用最新状态更新了它.最初编写时,在 Django 1.4(2012 年 3 月底发布)后不到一个月,它是正确的.但是从 Django 1.5 开始,获取用户名的正确方法是调用 get_username()
在用户模型实例上.由于能够交换 User
类(并将自定义字段作为用户名),因此已添加此功能.
Thanks to @buffer, who dug out this old answer, I have updated it with most recent state. When it was originally written, in less than a month after Django 1.4 (which was released at the end of March 2012), it was correct. But since Django 1.5, proper method to get username is to call get_username()
on user model instance. This has been added due to ability to swap User
class (and have custom field as username).
这篇关于Django 1.4 - {{ request.user.username}} 不在模板中呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!