In any web application, user experience is very crucial. One aspect of this is redirecting the users back to the page they were previously viewing after they log in.
For example, When users log in, especially if prompted to do so while trying to access a restricted page, it’s a good practice to redirect them back to the page they initially intended to visit. This improves the user experience by maintaining the flow of the application.
let’s see the step-by-step process of how to implement this
Capture the Previous Page URL
First, we need to capture the URL of the page the user was trying to access before we asked to log in. We can do this by using the next
parameter in the query string.
For example: If a user attempts to access http://example.com/restricted_page/
and is redirected to http://example.com/accounts/login/
, We can append the original URL to the login URL as a query parameter: http://example.com/accounts/login/?next=/restricted_page/
.
Update the Login View
In the login view, check for the next
parameter in the request. If it exists, redirect the user to that URL after a successful login.
from django.shortcuts import redirect
def login_view(request):
# ... Write your login logic here ...
# Redirect to 'next' parameter if it exists
next_page = request.GET.get('next')
if next_page:
return redirect(next_page)
return redirect('default-post-login-page')
Using @login_required
Decorator
We can use the Django’s built-in @login_required
decorator which automatically appends the next
parameter with the requested URL when redirecting unauthenticated users to the login page.
Following is the example:
from django.contrib.auth.decorators import login_required
@login_required
def restricted_view(request):
# Your view logic here