๐Ÿ“ Django

login_required: protecting views

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
246
๐ŸŒฟ
Level
Medium

Django can restrict a view to authenticated users with a decorator for function-based views or a mixin for class-based views.

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

๐Ÿ“

Search in Django

You can start with simple Django ORM filters and move to PostgreSQL features when you...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 279
๐Ÿ“

Swagger Documentation with drf-spectacular

drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 561
๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 315
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Django RequestLab: from HTTP to secure production Open course curriculum