Restrict Access with @login_required (FBV)
A snippet showing how to restrict access to a function-based view with @login_required.
# views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required
def dashboard_view(request):
return render(request, 'dashboard.html')
# templates/dashboard.html
<h2>Welcome to your dashboard</h2>
<p>Only logged-in users can see this.</p>
Explanation:
-
The
@login_requireddecorator protects views from unauthenticated access. - If a user is not logged in, they will be redirected to the login page automatically.
-
You can customize the login URL using
LOGIN_URLin Django settings. - Ideal for protecting dashboards, profiles, and any view that needs authentication.
- Category Authentication & Authorization
- Total Views 1494
- Last Modified 13 September, 2025
- Tags #login #decorator #fbv #auth
Previous snippet
Redirect After Successful Login
Next snippet