?next=/url-path/ does not redirect to the specified path after login

I have a simple conditional statement in my django template to check if a user is authenticated then redirect the user to the page there where on which in my case is http://127.0.0.1:8000/user/sign-in/?next=/detail/brigmjklyb/. Now, whenever i login, it redirects directly to the homepage and that is not what i want.

In my settings.py, i have specified these.

LOGIN_URL = "userauths:sign-in"
LOGIN_REDIRECT_URL = ""
LOGOUT_REDIRECT_URL = "userauths:sign-in"

and this is my login view

def loginViewTemp(request):
    if request.user.is_authenticated:
        messages.warning(request, "You are already logged in")
       
        return redirect('store:home')
    
    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')

        try:
            user = User.objects.get(email=email)

            user = authenticate(request, email=email, password=password)

            if user is not None:
                login(request, user)
                messages.success(request, "You are Logged In")
                // I am guessing the error is from here, but how do i redirect to the previous page there were on.
                return redirect('store:home')
            else:
                messages.error(request, 'Username or password does not exit.')
        
        except:
            messages.error(request, 'User does not exist')

    return render(request, "userauths/sign-in.html")

What can i possible be doing wrong here?

You’re probably right.
The ?next=/something/ is a query parameter in the request. So you can access it using request.GET that is a dict-like. So in this case, you can:

# Either redirect the user to the `next` url if any, or the home page
next_url = request.GET.get("next", "store:home")
return redirect(next_url)

This is possible because redirect allows you to pass either a url, or a “reversable” url name

2 Likes

Thanks alot, that fixed it for me.