The next
attribute in the url
can be handled inside the login function to navigate the user to the page he actually wanted to visit to instead of redirecting him to the default home page.
For example, lets create a demo page with a url http://127.0.0.1:8000/demo, which requires authentication.
First you can create a demo.html
file inside the templates folder and add the following code.
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo</title>
</head>
<body>
<h1>Demo Page</h1>
<h2>Welcome {{request.user}}</h2>
<h2>Restricted content to be accessed by only authenticated users</h2>
<a href="{% url 'logout' %}">Logout</a>
</body>
</html>
Now lets create a function to render this template and map it with a url.
Add a function in the authentication/views.py
file :
@login_required(login_url='login')
def demo(request):
return render(request, 'demo.html')
Also map it with a url in authentication/urls.py
file :
path("demo", views.demo, name='demo'),
After doing this when you try to visit http://127.0.0.1:8000/demo, you will be redirected to the login page along with the next attribute set to /demo
.
The next
attribute can be handled in the login function to navigate it to the particular page after logging in. Edit the login function as follows to handle the next
attribute :
def user_login(request):
if request.method == 'POST':
next = request.GET.get('next')
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
if next:
return redirect(next)
return redirect('home')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})
If the next
attribute is present, it will redirect it to the particular page, else it will redirect the user to the home page.
In our case, it will redirect the user to the demo page after login :