Django – login_required not redirecting

Question:

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/”

Asked By: Buggy Coder

||

Answers:

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

Answered By: Hasan Ramezani

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.

Answered By: Buggy Coder

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

Answered By: Almas Liaqat

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.

Answered By: wangjinliang1991

Clear the page cookies via chrome DevTool -> Application -> Storage -> Cookies can fix this.

Answered By: Allen Zheng

Alternatively, you can fix this error by just opening your app in Google Chrome’s Incognito Window.

Answered By: Sayyor Y

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.

Answered By: william

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.

Answered By: parkwarns
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.