I want to secure each webpage of my django app, and what I want is that after login the user should be redirected to the previous page he was trying to access. So in accounts/views.py this is the login function I am using for that:
def login(request):
if request.method == 'POST':
#some code
if user is not None:
auth.login(request, user)
return redirect(request.POST.get('next','dashboard'))
else:
#some code
else:
#some code
Now, I have used @login_required condition for each view of my webapp in this way:
@login_required(login_url='login')
def profile(request):
return render(request, 'profile.html')
my login.html (reference):
<form method="POST" action="/accounts/auth">
{% csrf_token %}
<input type="hidden" name="next" value="{{ request.GET.next }}" />
{{ login_form }}
<input type="submit">
</form>
Now if the user visits accounts/profile without login, then he is redirected to accounts/login?next=/accounts/profile, so after login he is successfully redirected to accounts/profile as the value of 'next' is set to /accounts/profile and in login function if the user is authenticated then i have used return redirect(request.POST.get('next','dashboard')) which means redirect to the value of next if it is entered, otherwise /accounts/dashboard.
Now coming to my issue, if I try to access the login page directly (i.e. /accounts/login) then as there is no next variable in the URL, so according to my login function I should be redirected to /accounts/dashboard but instead, I am getting the following error: Reverse for '' not found. '' is not a valid view function or pattern name. what am I doing wrong?
Extra note: I have even tried adding LOGIN_REDIRECT_URL='dashboard' to my settings.py but still when the next variable is blank I am not redirected to the dashboard
Mostly the mistake is in this piece of code:
redirect(request.POST.get('next','dashboard'))