📝 Django

login_required: protecting views

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
79
🌿
Level
Medium

If the user is not authenticated, they are redirected to settings.LOGIN_URL with the ?next=/current-url/ parameter.

Decorator for FBVs

from django.contrib.auth.decorators import login_required

@login_required
def my_profile(request):
    return render(request, 'profile.html', {'user': request.user})

# Custom login URL
@login_required(login_url='/custom/login/')
def secret_view(request):
    ...

If the user is not authenticated, they are redirected to settings.LOGIN_URL with the ?next=/current-url/ parameter.

LoginRequiredMixin for CBVs

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView

class TaskListView(LoginRequiredMixin, ListView):
    model = Task
    template_name = 'tasks/list.html'
    login_url = '/accounts/login/'        # where to redirect
    redirect_field_name = 'next'          # GET parameter name

The mixin must come first in the list of parent classes.

settings.LOGIN_URL

# settings.py
LOGIN_URL = '/accounts/login/'           # default
LOGIN_REDIRECT_URL = '/'                 # after successful login
LOGOUT_REDIRECT_URL = '/accounts/login/' # after logout

Checking authentication inside a view

def my_view(request):
    if not request.user.is_authenticated:
        return redirect('login')
    # code below only runs for authenticated users

UserPassesTestMixin — custom conditions

from django.contrib.auth.mixins import UserPassesTestMixin

class AdminOnlyView(UserPassesTestMixin, ListView):
    model = Task

    def test_func(self):
        return self.request.user.is_staff  # staff only

    def handle_no_permission(self):
        return redirect('home')  # custom redirect on denial

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 132
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 83
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 73

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!