0
0
Djangoframework~5 mins

login_required decorator in Django

Choose your learning style9 modes available
Introduction

The login_required decorator makes sure only logged-in users can see certain pages. It helps keep parts of your website private.

You want to protect a user profile page so only the owner can see it.
You have a dashboard that should only be visible after logging in.
You want to stop visitors from accessing settings or account pages without signing in.
You want to redirect users to the login page if they try to visit a protected page.
You want to keep some pages hidden from users who are not signed in.
Syntax
Django
from django.contrib.auth.decorators import login_required

@login_required
def your_view(request):
    # your code here
    return HttpResponse('Hello, user!')

Place @login_required right above your view function.

It automatically redirects users to the login page if they are not logged in.

Examples
This protects the dashboard page so only logged-in users can see it.
Django
from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    return HttpResponse('Welcome to your dashboard!')
You can customize the login page URL if you don't want to use the default.
Django
from django.contrib.auth.decorators import login_required

@login_required(login_url='/custom-login/')
def profile(request):
    return HttpResponse('User profile page')
Use it with views that render templates to protect pages like settings.
Django
from django.contrib.auth.decorators import login_required

@login_required
def settings(request):
    return render(request, 'settings.html')
Sample Program

This view shows a secret message only if the user is logged in. Otherwise, it sends them to the login page.

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

@login_required
def secret_page(request):
    return HttpResponse('This is a secret page for logged-in users only.')
OutputSuccess
Important Notes

Make sure LOGIN_URL is set in your Django settings or use the login_url parameter.

The decorator works only on function-based views, but you can use LoginRequiredMixin for class-based views.

It helps improve security by preventing unauthorized access easily.

Summary

login_required keeps pages private by allowing only logged-in users.

Use it by placing @login_required above your view functions.

It redirects users to the login page if they are not signed in.