Creating a website is fun, but a login restrictor in your website will make it look more secure. Django REST Framework is a robust and flexible toolkit for building Web APIs. The Django login required decorator provide the feature to restrict the access
We have often visited websites in which we need to log in first before accessing or visiting other pages. In other words, restricting access.

We also came across some of our projects where we need to do the same but wonder how? So yes you came to the right place, but before moving ahead let’s first sneak peek about the login decorator in Django Rest Framework. login_required() decorator does the following things:-
- Execute normally the view if the user is logged in.
- Redirect the user to the login_url path if the user is not logged in.
Syntax:-
@login_required(login_url=”html page”)
In this blog, we will understand how to restrict access with the Django login required decorator function? Where to use it? And all about it.
Step 1. Create Django Project
We are first going to create a Django project, an app inside that project.
- Create a Django project.
django admin startproject bloglogindecorator
- Create app in that django-project.
python manage.py startapp logindecorator
- Add your app name in installed apps.
Settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'logindecorator' ]
Step 2. Add files and Folder to the Django Project
We need to create a template folder in the Django folder and a urls.py file in the app folder.
- Create a new folder in the Django folder(here, bloglogindecorator) save it with the name template.
- Add the path for this template folder in bloglogindecorator> settings.py.
Settings.py
import os TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'template')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
3. Create a new file in the app folder(here, login decorator) save it with the name urls.py.
4. Add the path for this url.py file in bloglogindecorator > urls.py.
Urls.py
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('logindecorator.urls')) ]
Step 3. Login Decorator
- Add database. We are first going to add our database to our project. In settings.py add the below code according to your database in DATABASES.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'bloglogindecorator', 'USER': 'postgres', 'PASSWORD':"2320", 'HOST': 'localhost' } }
2. Migrate model
Run the below code to migrate your model into your database.
python manage.py makemigrations python manage.py migrate
3. Add login decorator to the functions which require the user to login first in logindecorator(your_app_name) > views.py. We will import login_requred from django.contrib.auth.decorators and place it before the functions where we need the user to login first following ‘@’ symbol and parameters are login_url which will specify the page to redirect if user is not login and clicking that page.
Syntax:-
@login_required(login_url=”html page”)
Views.py
from django.shortcuts import render from django.contrib.auth.models import User,auth from django.contrib import messages from django.contrib.auth.decorators import login_required # Create your views here. def index(request): return render(request,'index.html') @login_required(login_url='index') def about(request): return render(request,'about.html') @login_required(login_url='index') def faq(request): return render(request,'faq.html') def login(request): return render(request,'login.html') def signup(request): return render(request,'signup.html') def login1(request): if request.method=='POST': username=request.POST['username'] pass1=request.POST['password'] user=auth.authenticate(username=username,password=pass1) if user is not None: auth.login(request,user) return render(request,'index.html') else: messages.info(request,'Invalid credentials') return render(request,'login.html') else: return render(request,'login.html') def signup1(request): if request.method=="POST": username=request.POST['username'] pass1=request.POST['password'] pass2=request.POST['password1'] if pass1==pass2: if User.objects.filter(username=username).exists(): messages.info(request,'OOPS! Usename already taken') return render(request,'signup.html') else: user=User.objects.create_user(username=username,password=pass1) user.save() messages.info(request,'Account created successfully!!') return render(request,'login.html') else: messages.info(request,'Password do not match') return render(request,'signup.html') def logout(request): auth.logout(request) return render (request,'index.html')
4. Create Url path for the function in logindecorator(your_app_name)>urls.py.
Urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index,name='index'), path('login',views.login,name="login"), path('login1',views.login1,name="login1"), path('signup',views.signup,name="signup"), path('signup1',views.signup1,name="signup1"), path('about',views.about,name="about"), path('faq',views.faq,name="faq"), path('logout',views.logout,name="logout"), ]
5. Add function in index html page to show the links only when user is logged in otherwise show login and signup link only.
Index.html
<html> <head> <title> INDEX </title> <style> .bodycontainer { background-color: rgb(214, 228, 165); height: 500px; } .menucontainer { background-color: darkorange; } .menucontainer a { text-decoration: None; color: #fff; font-size: 20px; padding-top: 2px; } .menucontainer ul { margin-left: 900px; margin-top: 50px; } .menucontainer li { display: inline; padding-left: 15px; } </style> </head> <body> <div class="container1"> <div class="menucontainer"> <ul> <li><a href="/">Home</a></li> <li><a href="about">About</a></li> <li><a href="faq">FAQ</a></li> <li><a href="login">Login</a></li> <li><a href="signup">Signup</a></li> </ul> </div> <div class="bodycontainer"> <h1>This is home page</h1> <h3>Welcome {{user.username}}</h3> </div> </div> </body> </html>
Output :-
Before Logged In :-

After Log In :-

Quick Revision:-
- Create your django project folder.
- Create an app folder in the django project folder.
- Add template folder in the django folder and provide its path in django_folder > settings.py .
- Create file named as urls.py in the app folder and provide its path in django_project > urls.py.
- Add login decorator to the function in app_folder > views.py.
- Add restriction to pages in html code in django_project > template > index.html.