[英]Django login_required passes but then user.is_authenticated fails in the template (??)
This view function: 此视图功能:
@login_required
def dashboard(request):
from myproject.myapp.models import UserProfile
k = UserProfile.objects.get( user=request.user.pk ).known
return render_to_response('dashboard.html', {'KNOWN': k, , context_instance=RequestContext(request))
Passes to this template: 传递给此模板:
{% if user.is_authenticated %}
{{ user.username }}
{% else %}
Login link
{% endif %}
{{ KNOWN }}
How is this possible? 这怎么可能? Surely if login_required works, and it managed to grab KNOWN, therefore user must exist somewhere?
当然,如果login_required可以正常工作,并且设法获得了KNOWN,那么用户必须存在于某个地方吗?
How can I debug this? 我该如何调试?
:-) :-)
UPDATE: If I remove: 更新:如果我删除:
TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.request',)
From settings, it works. 通过设置,它可以工作。
However, by removing that, other pages which use {{ request.get_full_path }} in templates don't load. 但是,通过删除该页面,不会加载模板中使用{{request.get_full_path}}的其他页面。
Eeek. Eeek。
UPDATE 2: 更新2:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.request",)
If you just add the request line on its own, it disables all the others which are defaults. 如果仅添加请求行,则会禁用所有其他默认行。 D'Oh!
D'哦!
UPDATE 3: Thought that would fix it, unfortunately still not working. 更新3:认为可以解决此问题,但仍然无法正常工作。
UPDATE 4: Spotted typo elsewhere, can confirm that Mark Lavin's answer fixed it :) 更新4:在其他地方发现错别字,可以确认马克·拉文的答案已解决:)
If you are setting TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.request',)
then you are removing all the default context processors in particular django.contrib.auth.context_processors.auth
which adds user
to the context. 如果您设置
TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.request',)
那么您将删除所有默认上下文处理器,尤其是django.contrib.auth.context_processors.auth
,它将user
添加到上下文中。 You should instead use 您应该改用
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
)
You should keep django.core.context_processors.request, it allows to use the {{ request }} in templates. 您应该保留django.core.context_processors.request,它允许在模板中使用{{request}}。
The request object features a user property which should correspond to the user requesting the page. 请求对象具有用户属性,该属性应与请求页面的用户相对应。
Try this, it should work for you too: 试试这个,它也应该为您工作:
{% if request.user.is_authenticated %}
you're authenticated as {{ request.user.username }}
{% else %}
i'm a guest
{% endif %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.