用户身份验证模板标签不起作用-Django
我使用 django 注册应用程序。一切都很顺利。用户通过电子邮件验证进行注册,但当用户登录并重定向到主页时,身份验证模板标签(例如 {% if user.is_authenticated %})返回 false。
我的 login.html 中有这个
<input type="hidden" name="next" value="/" />
登录后我想将用户重定向到主页和 mainpage.html
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
但 user.is_authenticated 在此处返回 false 。这里可能有什么问题?谢谢
I used django-registration app. Everything goes fine. User gets registered with email verification but when user logs in and is redirected to mainpage the auth template tags such as {% if user.is_authenticated %} returns false.
I am having this in my login.html
<input type="hidden" name="next" value="/" />
After login I want to redirect the user to main page and in mainpage.html
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
but user.is_authenticated returns false here. What might be the problem here? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
{% if request.user.is_authenticated %}
代替。用户完全有可能没有被传递到视图中的上下文字典中。如果在模板中找不到该对象,它将跳到块的其他部分。渲染模板在 django 中很奇怪,因为通常属于例外的内容被吞掉了。Try using
{% if request.user.is_authenticated %}
instead. It's entirely possible that user isn't being passed into the context dictionary within the view. If the object is not found within the template, it will just skip to the else portion of the block. Rendering templates are strange in django, as what would normally be an exception, is swallowed.您能向我们展示处理 URL“/”的视图的代码吗?我认为这就是你的问题所在,而不是你使用 django-registration 的问题。
此视图是否将
user
放入上下文中?如果您想在模板中使用它,则必须将其放入。如果您想在上下文中使用request
,那么您需要确保传递一个实例RequestContext
作为上下文而不仅仅是标准上下文对象。Can you show us the code for the view which handles the URL '/'? I think this is where your problem lies, rather than in your use of django-registration.
Does this view put
user
in the context? If you want to use it in the template, you're going to have to put it in. If you want to userequest
in the context, then you need to make sure that you pass an instance ofRequestContext
as the context rather than just a standard context object.这对我有用。
假设您的
主页
由views.py
中的视图处理,您需要添加RequestContext以包含到用户对象中。将您的视图更改为
Here's what worked for me.
Suppose your
main page
gets processed by a view inviews.py
You need to add RequestContext to include to user object. Change your view to