0
0
DjangoHow-ToBeginner · 3 min read

How to Use login_required Decorator in Django for Access Control

Use the login_required decorator from django.contrib.auth.decorators to restrict access to views only for logged-in users. Apply it by placing @login_required above your view function to automatically redirect unauthenticated users to the login page.
📐

Syntax

The login_required decorator is imported from django.contrib.auth.decorators. You apply it by placing @login_required above a view function. This ensures only authenticated users can access that view. If a user is not logged in, they are redirected to the login page.

You can customize the redirect URL by passing login_url as an argument.

python
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    # Your view logic here
    pass

# With custom login URL
@login_required(login_url='/custom-login/')
def another_view(request):
    pass
💻

Example

This example shows a simple Django view protected by login_required. If a user tries to access /dashboard/ without logging in, they will be redirected to the default login page at /accounts/login/.

python
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

@login_required
def dashboard(request):
    return HttpResponse('Welcome to your dashboard!')
Output
When accessing /dashboard/: - If logged in: Displays 'Welcome to your dashboard!' - If not logged in: Redirects to /accounts/login/?next=/dashboard/
⚠️

Common Pitfalls

  • Forgetting to import login_required causes errors.
  • Not applying the decorator to the view means no access control.
  • Using login_required on class-based views requires a different approach (LoginRequiredMixin).
  • Not setting LOGIN_URL in settings.py or passing login_url can cause unexpected redirects.
python
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

# Wrong: missing decorator

def profile(request):
    return HttpResponse('User profile')

# Right: with decorator
@login_required
def profile(request):
    return HttpResponse('User profile')
📊

Quick Reference

FeatureDescription
@login_requiredDecorator to restrict access to authenticated users
login_urlOptional argument to specify custom login redirect URL
Default redirectRedirects to /accounts/login/ if not logged in
Class-based viewsUse LoginRequiredMixin instead of decorator
SettingsSet LOGIN_URL in settings.py to change default login page

Key Takeaways

Use @login_required above view functions to restrict access to logged-in users.
Unauthenticated users are redirected to the login page automatically.
Customize the login redirect URL with the login_url parameter or LOGIN_URL setting.
For class-based views, use LoginRequiredMixin instead of the decorator.
Always import login_required from django.contrib.auth.decorators before use.