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_required decorator 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_URL in Django settings.
  • Ideal for protecting dashboards, profiles, and any view that needs authentication.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.