Last modified: Jan 10, 2023 By Alexander Williams

How to use login_required with Django CBV

In this tutorial, we'll learn how to use login_required with Django Class Based View.

1. creating a simple TemplateView

to understand how use login_required with CBV, let's create a simple TemplateView.

from django.views.generic.base import TemplateView

class LoginRequiredView(TemplateView):

    template_name = "page.html"

In, we need to add a path for our view.

    path('page/', LoginRequiredView.as_view()),


<!DOCTYPE html>

<h1>Hello User</h1>



How to use login_required with Django CBV

2. Using login_required with django CBV

we have two options to set login_required to Django CBV, LoginRequiredMixin login_required()

1. LoginRequiredMixin

we'll use the first option in

from django.contrib.auth.mixins import LoginRequiredMixin

class LoginRequiredView(LoginRequiredMixin, TemplateView):

    template_name = "page.html"
    redirect_field_name = '/admin/login/?next=/admin/'

remember! you must add LoginRequiredMixin before TemplateView.

redirect_field_name: URL that you want browser redirected if the user the has not logged.

2. login_required()

the second option, we'll use it in

from django.contrib.auth.decorators import login_required

path('page/', login_required(LoginRequiredView.as_view(), login_url='/admin/login/?next=/admin/')),

Happy Coding!