Discover how a tiny tag can save you hours of repetitive security checks!
Why login_required decorator in Django? - Purpose & Use Cases
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.
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 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.
def secret_page(request): if not request.user.is_authenticated: return redirect('login') return render(request, 'secret.html')
@login_required def secret_page(request): return render(request, 'secret.html')
You can protect many pages easily and consistently, making your website secure without repeating code.
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.
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.