Login_redirect_url not working. View always redirecting to index

Viewed 315

This is my login redirect url in settings.py:

LOGIN_REDIRECT_URL='/category/all'

And this is my login view:

def login(request):

    if request.user.is_authenticated:
        return redirect('/')
    else:
        if request.method == "POST":
            email=request.POST['email']
            password=request.POST['password']
            user=auth.authenticate(email=email,password=password)

            if user is not None:
                auth.login(request, user)
                return redirect('/')
            else:
                messages.info(request,"Email Password didn't match")
                return redirect('login')
        else:
            return render(request,"login.html")

Whenever the user logs in I want to redirect him to the category/all page but it is always redirecting to index("/") and this might be because I am using return redirect("/").Also even when I have login required for some view then too even when the url is like:

http://localhost:8000/login/?next=/cart/

Instead of redirecting me to cart it redirects too index. Please help me to work around this so that the redirect works properly.

2 Answers

You constructed your own login view, hence that means that the mechanism to redirect will not work, since the LOGIN_REDIRECT_URL, etc. are parameters for the LoginView [Django-doc] of the Django auth module.

You can simply redirect in your view:

def login(request):
    if request.user.is_authenticated:
        return redirect('/category/all')
    else:
        if request.method == 'POST':
            email=request.POST['email']
            password=request.POST['password']
            user=auth.authenticate(email=email,password=password)

            if user is not None:
                auth.login(request, user)
                # redirect to a view
                return redirect('/category/all')
            else:
                messages.info(request, "Email Password didn't match")
                return redirect('login')
        else:
            return render(request,'login.html')

In the code, you are using return redirect('/') statement, which is redirecting you to home page.

To handle the redirections of urls like this - http://localhost:8000/login/?next=/cart/ you need to get value of next parameter from url, then write statement something like this. (Add this where you are using "return redirect('/')" statement)

next = request.GET.get('next') if next: return redirect(next) else: return redirect('/')

Sorry for not formatting properly,, I m posting from mobile

Related