0
0
Djangoframework~3 mins

Why login_required decorator in Django? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a tiny tag can save you hours of repetitive security checks!

The Scenario

Imagine building a website where some pages should only be seen by users who have logged in. You try to check on every page if the user is logged in by writing the same code again and again.

The Problem

Manually checking login status on every page is tiring and easy to forget. If you miss it even once, unauthorized users can see private pages. It also makes your code messy and hard to maintain.

The Solution

The login_required decorator lets you add a simple tag above your page functions. It automatically blocks users who are not logged in and sends them to the login page, keeping your code clean and safe.

Before vs After
Before
def secret_page(request):
    if not request.user.is_authenticated:
        return redirect('login')
    return render(request, 'secret.html')
After
@login_required
def secret_page(request):
    return render(request, 'secret.html')
What It Enables

You can protect many pages easily and consistently, making your website secure without repeating code.

Real Life Example

A social media site where only logged-in users can see their messages and profile settings, all protected simply by adding @login_required above the view functions.

Key Takeaways

Manually checking login on every page is error-prone and repetitive.

login_required decorator automates login checks cleanly.

It helps keep your site secure and your code simple.