Redirect After Successful Login
A snippet for redirecting users to a specific page after they log in successfully.
# views.py
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
from django.contrib import messages
def login_view(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
next_url = request.GET.get('next') or 'dashboard' # fallback to 'dashboard'
return redirect(next_url)
else:
messages.error(request, 'Invalid credentials')
return render(request, 'login.html')
# templates/login.html
<form method="POST">
{% csrf_token %}
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
{% if messages %}
{% for message in messages %}
<p>{{ message }}</p>
{% endfor %}
{% endif %}
Explanation:
- After a successful login, we want to redirect users to their dashboard or a page they originally intended to visit.
-
The
nextparameter captures the original URL the user tried to access before logging in. -
If no
nextparameter is found, we redirect to a default page like'dashboard'. - This approach improves user experience by returning them to the right place after login.
- Category Authentication & Authorization
- Total Views 941
- Last Modified 11 September, 2025
- Tags #login #redirect #auth #fbv
Previous snippet
Logout with logout()
Next snippet