简体   繁体   中英

django login_required not redirecting

I'm new to Django, so bear with me. 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. (No error, no redirect, nothing.)

Here is what I have relating to this issue:

project settings.py

LOGIN_URL = '/login'

app 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

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. Does next have anything to do with this problem? 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. You should do:

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

or even better, drop the context variable altogether and just do

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

(since render, unlike render_to_response, uses RequestContext by default).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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