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.

views.py


from django.views.generic.base import TemplateView

class LoginRequiredView(TemplateView):

    template_name = "page.html"

urls.py

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


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

page.html


<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<h1>Hello User</h1>

</body>
</html>

Result:

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 views.py


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 urls.py


from django.contrib.auth.decorators import login_required

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

Happy Coding!