简体   繁体   中英

Django - login_required not redirecting

I'm trying to make a view restricted unless login is done. Was following tuts+plus django unchained tutorial

However login_required decorator somehow is not doing the job. What am I doing wrong?

that part at views.py (login_required has been imported)

@login_required
def story(request):
    if request.method == "POST":
        form = StoryForm(request.POST)
        if form.is_valid():
                form.save()
                return HttpResponseRedirect('/')
    else:
        form = StoryForm()
    return render(request, 'stories/story.html', {'form': form})

no changes has been brought in urls.py. So I am hoping for an error where it can't find /login. But that somehow is not happening.

settings.py has LOGIN_URL = "/login/"

I'm not sure why this is happening. But for some reason in chrome the default story view is opening without redirecting to /login whereas it is working fine in Firefox. I tried clearing the cached images & files in Chrome, but it didn't help.

For now I'll just use Firefox to get through it.

Add an entry in urls.py like this:

(r'^login/$', 'login_view'),

Or you can use remove LOGIN_URL = "/login/" from your settings.py and use:

@login_required(login_url='/login/')

in both case you must add entry to urls.py

I had the same issue. I cleared Chrome chache but it didn't work . Now i am running it on Firefox and its running correctly

Make sure your chrome browser has cleared all of the browsing data, mind that time range choice all time, and then you will solve this problem. I alse encountered this issue, after using Firefox to work well, I got it.

通过 chrome DevTool -> Application -> Storage -> Cookies 清除页面 cookie 可以解决这个问题。

或者,您可以通过在 Google Chrome 的Incognito Window打开您的应用程序来修复此错误。

I had the same problem and I realized the browser identifies me as a logged-in user because I had logged in before as administrator in the admin page. I logged out of the admin page and the login_required decorator worked correctly.

I was able to resolve this by using the logout() function imported the same way as login() and that essentially "cleared" any existence of my already logged in user.

Make a logout view function/url route, run the app and call the url, then you will no longer be able to access the other view functions with the decorator unless logged in once again.

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