How to return back to the same page when we use user_passes_test decorator in Django

When I sign in or log in to my account, I do not want to go back to the login page or registration page by giving the URL in the address bar. What I want is to stay on the same page even after giving the registration or login page URL. For that, I have used the user_passes_test decorator in the views.py file. Also, I set login_url in the user_passes_test decorator as return redirect(request.META['HTTP_REFERER']). At that time I got a Page not found (404) error.

views.py

from django.contrib.auth.decorators import user_passes_test

@user_passes_test(user_is_not_logged_in, login_url="return redirect(request.META['HTTP_REFERER'])", redirect_field_name=None)
def register(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = UserForm()
    return render(request, 'register.html', {'form': form})

Can anyone suggest a solution to solve this issue?

Back to Top