简体   繁体   English

Django login_required不重定向

[英]django login_required not redirecting

I'm new to Django, so bear with me. 我是Django新手,请多多包涵。 I am trying to make a page that the user has to be logged in to visit using @login_required , but it doesn't seem to be doing anything whatsoever. 我正在尝试创建一个页面,用户必须使用@login_required登录才能访问该@login_required ,但是它似乎没有任何作用。 (No error, no redirect, nothing.) (没有错误,没有重定向,什么都没有。)

Here is what I have relating to this issue: 这是我与此问题有关的内容:

project settings.py 项目settings.py

LOGIN_URL = '/login'

app views.py 应用views.py

from django.contrib.auth.decorators import login_required

@login_required
def index(request):
    context = RequestContext(request)
    return render_to_response('evaluation/index.html')

project urls.py 项目urls.py

url(r'^login/$', 'django.contrib.auth.views.login')

I don't know if this is related either, but on this page where I want login to be required, I have it set up that it should show the username if logged in, but it doesn't do that, either, even after I seem to successfully log in and am redirected by my login page: 我也不知道是否与此相关,但是在我要登录的页面上,我已经设置好了它,如果登录了它应该显示用户名,但是即使在之后,它也不会这样做。我似乎已成功登录,并被登录页面重定向:

{% if user.is_authenticated %}
<h1>Hello {{ user.username }}</h1>
{% else %}
<h1>Hello world</h1>
{% endif %}

I have looked at the documentation for django.contrib.auth, but it hasn't been useful. 我看过django.contrib.auth的文档,但是它没有用。 Does next have anything to do with this problem? next与这个问题有关系吗? I still can't figure out what on earth that is or does, despite my googling. 尽管进行了谷歌搜索,但我仍然不知道到底是什么还是在做什么。 (If anyone has suggestions for good resources related to this, that would also be appreciated.) (如果有人对与此相关的良好资源提出建议,也将不胜感激。)

You're not passing your context to the template in index , so it knows nothing about the user variable. 您没有将上下文传递给index的模板,因此它对user变量一无所知。 You should do: 你应该做:

return render_to_response('evaluation/index.html', context)

or even better, drop the context variable altogether and just do 甚至更好,完全删除context变量,然后执行

return render(request, 'evaluation/index.html')

(since render, unlike render_to_response, uses RequestContext by default). (因为render与render_to_response不同,默认情况下使用RequestContext)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM