Episode 24 of 32
Requiring Login
Protect views with the login_required decorator — redirect unauthenticated users to the login page before accessing restricted content.
Requiring Login
Some pages should only be accessible to logged-in users. Django provides the login_required decorator to protect views.
Using login_required
# articles/views.py
from django.contrib.auth.decorators import login_required
@login_required(login_url='accounts:login')
def article_create(request):
# Only logged-in users can reach this view
return render(request, 'articles/article_create.html')
If a user is not logged in and tries to visit this page, they are redirected to the login page. After logging in, they are sent back to the page they originally requested.
How It Works
User visits /articles/create/ (not logged in)
↓
@login_required checks request.user.is_authenticated
↓
False → Redirect to /accounts/login/?next=/articles/create/
↓
User logs in
↓
Redirect to /articles/create/ (the original page)
The ?next Parameter
When login_required redirects to login, it adds ?next=/original/path/ to the URL. After login, you can use this to redirect back. We will implement this in a later episode.
Protecting Multiple Views
@login_required(login_url='accounts:login')
def article_create(request):
# ...
@login_required(login_url='accounts:login')
def article_edit(request, slug):
# ...
# Public views — no decorator
def article_list(request):
# Anyone can see the article list
# ...
Key Takeaways
@login_requiredprotects views — only authenticated users can access themlogin_urlspecifies where to redirect unauthenticated users- The
?nextparameter remembers the original URL for post-login redirect - Apply the decorator to views that should not be public