I am new to Django. I needed to code the login feature to redirect to originally requested URL after login. I looked around and found the following on a stackoverflow thread.
django redirect after login not working "next" not posting?
I see the following in the Django documention
login_required() does the following:
If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string. Example: /accounts/login/?next=/polls/3/.
I also read that the login() method of django.contrib.auth package passes next to the template. So I defined the login() function in my view (I cannot use the one from the 'auth' package since I need some customization).
def login(request):
next = request.GET['next']
return render(request, 'user/login.html', {'next': next})
In my template
<form method="post" action="{% url 'user:login_user' %}" >
{% csrf_token %}
<p><label for="id_username">Username:</label> <input autofocus="" id="id_username" maxlength="254" name="username" type="text" required /></p>
<p><label for="id_password">Password:</label> <input id="id_password" name="password" type="password" required /></p>
<input type="hidden" name="next" value="{{next}}" />
<button type="submit">Login</button>
</form>
In my login_user() function, if I see that the value of next is present, I redirect to that URL once I have logged the user in. This works for me fine.
However, solution presented in the thread above was a bit more involved. I am curious as to why is it necessary to do all that. What am missing here?
Thanks