How to restrict access with Django login required decorator function? - Django Tutorial (2023)

Last updated on 11th June 2021 by [emailprotected] | Category: Django Tutorial

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.

Built-In Login and Logout Authentic...

(Video) Python Basics Tutorial How to Restrict Access With Django Login Required Decorator Function

Built-In Login and Logout Authentication System in Django

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:-

  1. Execute normally the view if the user is logged in.
  2. Redirect the user to the login_url path if the user is not logged in.


@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.

(Video) How to use login_required decorator In Django

  1. Create a Djangoproject.
django admin startproject bloglogindecorator
  1. Create app in that django-project.
python startapp logindecorator
  1. Add your app name in installed apps.

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 file in the app folder.

  1. Create anew folderin the Django folder(here, bloglogindecorator) save it with the name template.
  2. Add the path for this template folder inbloglogindecorator>

import osTEMPLATES = [{'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 anew filein the app folder(here, login decorator) save it with the

4. Add the path for this file inbloglogindecorator >

from django.contrib import adminfrom django.urls import path,includeurlpatterns = [path('admin/',,path('',include('logindecorator.urls'))]

Step 3. Login Decorator

  1. Add database. We are first going to add our database to our project. In 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.

(Video) 17 | Prevent user accessing pages by Inbuilt decorator 'login_required' | Django | by Hardik Patel

python makemigrationspython migrate

3. Add login decorator to the functions which require the user to login first in logindecorator(your_app_name) > 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.


@login_required(login_url=”html page”)

from django.shortcuts import renderfrom django.contrib.auth.models import User,authfrom django.contrib import messagesfrom 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'),'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(),'OOPS! Usename already taken')return render(request,'signup.html')else:user=User.objects.create_user(username=username,password=pass1),'Account created successfully!!')return render(request,'login.html'),'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)>

from django.urls import pathfrom . import viewsurlpatterns = [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.


(Video) User Role Based Permissions & Authentication | Django (3.0) Crash Course Tutorials (pt 15)

<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 :-

How to restrict access with Django login required decorator function? - Django Tutorial (2)

After Log In :-

How to restrict access with Django login required decorator function? - Django Tutorial (3)

Quick Revision:-

  1. Create your django project folder.
  2. Create an app folder in the django project folder.
  3. Add template folder in the django folder and provide its path indjango_folder > .
  4. Create file named as in the app folder and provide its path indjango_project >
  5. Add login decorator to the function in app_folder >
  6. Add restriction to pages in html code in django_project > template > index.html.

GitHub link:-

« Email and Social Login using Django

How to Generate a QR Code in Django »

(Video) Django Tutorial - Django Decorators and email login #10


How to restrict user access in Django? ›

Django admin allows access to users marked as is_staff=True . To disable a user from being able to access the admin, you should set is_staff=False . This holds true even if the user is a superuser. is_superuser=True .

How to use login_required decorator in Django? ›

Create an app folder in the django project folder. Add template folder in the django folder and provide its path in django_folder > . Create file named as in the app folder and provide its path in django_project > Add login decorator to the function in app_folder >

How do I bypass Django username and password? ›

from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...

How to use login required in Django class based view? ›

Now let's look at it as a class-based view:
  1. from django. views. generic import View. ...
  2. template_name = 'authentication/login.html' form_class = forms. LoginForm. ...
  3. form = self. form_class() message = '' ...
  4. def post(self, request): form = self. ...
  5. username=form. cleaned_data['username'], ...
  6. login(request, user) return redirect('home')
Feb 3, 2022

How do I restrict access to users? ›

Four ways to restrict access to confidential data
  1. Use minimum privileges. Only give your employees access to the information they require to perform their specific roles. ...
  2. Employ multi-factor authentication. ...
  3. Electronic signatures. ...
  4. Data encryption. ...
  5. Limit access to your data with Galaxkey.

How do I restrict permissions? ›

Set an expiration date for a file

Open the file. Go to File. On the Info tab, select Protect Document, point to Restrict Permission by People, and then select Restricted Access. In the Permissions dialog box, select the Restrict permission to this document check box, and then select More Options.

What does {% %} do in Django? ›

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {% include %} do in Django? ›

The include tag allows you to include a template inside the current template. This is useful when you have a block of content that is the same for many pages.

How to create custom login view in Django? ›

To open the Django shell, run python shell .
  1. Step 1: Create a User. Import your custom User model into the Django shell. ...
  2. Step 2: Test the Login Functionality. ...
  3. Step 3: Create a Logout View. ...
  4. Step 4: Add the Logout View to the URL Patterns. ...
  5. Step 5: Add the Logout Template.
Feb 3, 2022

How do I bypass username and password? ›

We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL. Let us make an attempt to handle the below browser authentication.

How do you bypass a login password? ›

In the Command Prompt window, type net user username “” and press Enter. Replace username with your actual Windows account name. This will reset your Windows 10 password to blank. Close the Command Prompt window and click Sign in on the login screen to log in to Windows 10 without a password.

What is {% block title %} in Django? ›

The block tag has two functions: It is a placeholder for content. It is content that will replace the placeholder.

How do I create a separate login for administrator and user in Django? ›

Run the following command:
  1. $ python createsuperuser. Enter your desired username and press enter.
  2. Username: admin. You will then be prompted for your desired email address:
  3. Email address: ...
  4. Password: ********** Password (again): ********* Superuser created successfully.

How do I create a login and signup page in Django? ›

A Guide to User Registration, Login, and Logout in Django
  1. Create the register form.
  2. Create a register.html file.
  3. Add a register URL to the app.
  4. Add a register function to the views.
  5. Test the register user functionality.

How does Django handle login? ›

Overview. The Django authentication system handles both authentication and authorization. Briefly, authentication verifies a user is who they claim to be, and authorization determines what an authenticated user is allowed to do. Here the term authentication is used to refer to both tasks.

Can we use permission set to restrict access? ›

Permissions are additive which means we can't remove a user's existing permissions by assigning a permission set we can only add permissions. To limit access for a user or group of users, ensure that their base profile as well as any of their permission set limits this type of access.

Can permission set restrict access? ›

Permission sets grant additional permissions to specific users, on top of their existing profile permissions, without having to modify existing profiles, create new profiles, or grant an administrator profile where it's not necessary.

Why restrict user access? ›

By limiting user access, you narrow the amount of data employees have access to — and incidentally can compromise — without having to go through any of your network's other defenses. This is a smart practice that we always recommend to every client to increase their organization's network and device security.

What are the 3 types of permissions? ›

Permission Types

Files and directories can have three types of permissions: read, write, and execute: Someone with read permission may read the contents of a file, or list the contents of a directory.

Why is {% extends %} tag used? ›

The extends tag is used to declare a parent template. It should be the very first tag used in a child template and a child template can only extend up to one parent template. To summarize, parent templates define blocks and child templates will override the contents of those blocks.

What does %% in Python do? ›

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem.

What does _SET do in Django? ›

The _set is a reverse lookup class variable django puts in for you. The reason the reverse is a queryset is, ForeignKey is 1-to-many relationship. Hence, the reverse is a queryset. The _set object is made available when related_name is not specified.

What does _() mean in Django? ›

_ in Django is a convention that is used for localizing texts. It is an alias for ugettext_lazy.

What is URL mapping in Django? ›

It's where you define the mapping between URLs and views. A mapping is a tuple in URL patterns like − from django. conf. urls import patterns, include, url from django.

What are Django URLs? ›

Every page on the Internet needs its own URL. This way your application knows what it should show to a user who opens that URL. In Django, we use something called URLconf (URL configuration). URLconf is a set of patterns that Django will try to match the requested URL to find the correct view.

How to modify Django login form? ›

You can achieve this using following steps.
  1. Render the template as you are rendering right now (using {{form. as_p}}).
  2. Inspect elements and check user name, password and submit button's name and ids generated by default auth form.
  3. Recreate same tags using your own custom style.
Mar 27, 2019

How do I create a custom login and registration page? ›

Let's go - here are the main steps:
  1. Install and activate the user registration plugin.
  2. Activate the user registration add-on.
  3. Create a custom login form.
  4. Create a custom registration form.
  5. Customize the WordPress login and registration page.

How do I create a login authentication in Python? ›

Password Authentication using Python
  1. Create a dictionary of usernames with their passwords.
  2. Then you have to ask for user input as the username by using the input function in Python.
  3. Then you have to use the getpass module in Python to ask for user input as the password.
May 2, 2021

Which function is used to pass username and password when additional authentication is needed? ›

Enable a Multi-Factor Authentication Strategy.

A multi-factor authentication strategy is one that verifies users' identities using multiple methods of authentication. For example, a user could input their username and password, which then directs them to a one-time emailed link or security code.

What can hackers do with your username and password? ›

If hackers gain access to your passwords, they can do serious damage to your finances, reputation, and online identity. Once someone knows your login credentials, they could: Access your email and social media accounts. Make fraudulent purchases and transfers using your bank accounts.

What is the type of authentication that requires a username and password? ›

For purposes of user identity, users are typically identified with a user ID, and authentication occurs when the user provides credentials such as a password that matches their user ID. The practice of requiring a user ID and password is known as single-factor authentication (SFA).

How do I get around administrator restrictions? ›

On your Window's Home screen, press "Windows logo key" + "R" to open Run dialog box. Type the command “netplwiz” and hit Enter. A new interface will popup. Here, uncheck the box that reads: “Users must enter a username and password to use this computer”.

How to restrict IP address in Django? ›

  1. pip install django-block-ip.
  2. Add block_ip to your INSTALLED_APPS .
  3. Add block_ip. middleware. BlockIPMiddleware to your MIDDLEWARE_CLASSES .
  4. Run syncdb .
  5. Add one or more entries to the BlockIP list in the admin. You can just enter a single IP or use a network mask, like this:

How to whitelist IP in Django? ›

Turning on or off, and configuring the IP whitelist is done either via variables in your Django settings, or via environment variables. Values in Django settings take preference over values in the environment. Turning on/off the middleware is done via RESTRICT_IPS, and the default value is False.

What is block super in Django? ›

From the Django documention: "If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it.

How do I restrict multiple logins? ›

So, let's start the step by Step process of implementation.
  1. Step 1: Create Table tbl_user to store login access of user. ...
  2. Step 2: Create Table tbl_user_token to store dynamic created token value during login of user. ...
  3. Step 3: Create HTML Login page i.e. login. ...
  4. Step 4: Create authenticate. ...
  5. Step 5: create checkSession.
Apr 22, 2020

How do I enable login as a different user? ›

You cannot login as another user if you're already logged in as a user.
  1. Click the gear icon > Setup.
  2. Enter Login Access Policies in the Quick Find box.
  3. Select the Administrators Can Log in as Any User checkbox.
  4. Click Save.

Which types of users are allowed to login to the Django administration site? ›

In order to log into the admin site, we need a user account with Staff status enabled. In order to view and create records we also need this user to have permissions to manage all our objects. You can create a "superuser" account that has full access to the site and all needed permissions using

How to prevent multiple logins from same user in Django? ›

Django middleware that prevents multiple concurrent logins. If a user is already logged into the Django application and tries to log in somewhere else, the previous session is deleted. This package is based on code from and

Can we create user without password in Django? ›

Programmatically, you can create / save a new User without a password argument, and it will not raise any exceptions. In fact, you can even create a user without any arguments.

How do I connect my login and signup page to my database? ›

  1. Step 1- Create a HTML PHP Login Form. To create a login form, follow the steps mentioned below: ...
  2. Step 2: Create a CSS Code for Website Design. ...
  3. Step 3: Create a Database Table Using MySQL. ...
  4. Step 4: Open a Connection to a MySQL Database. ...
  5. Step 5 - Create a Logout Session. ...
  6. Step 6 - Create a Code for the Home Page.

How do I restrict access to parts of Django admin? ›

Django admin allows access to users marked as is_staff=True . To disable a user from being able to access the admin, you should set is_staff=False . This holds true even if the user is a superuser. is_superuser=True .

How to authenticate user login in Django? ›

from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...

How to set permissions in Django? ›

With Django, you can create groups to class users and assign permissions to each group so when creating users, you can just assign the user to a group and, in turn, the user has all the permissions from that group. To create a group, you need the Group model from django. contrib. auth.

How do I define user roles and permissions in Django? ›

Add Permissions to a Group

If you are using AbstractUser in Django, you must add AUTH_USER_MODEL = 'YourAppName. YourClassName' . This way, you are telling Django to use our custom user model instead of the default one. The code below should go in your file so that you can see your user model.

Can you restrict permission for users using permission set? ›

Yes, it is possible to restrict permission for users using permission set in salesforce. It's easy to manage users' permissions and access with permission sets because you can assign multiple permission sets to a single user.

How to secure Django admin? ›

10 tips for making the Django Admin more secure
  1. Use SSL. Deploy your site behind HTTPS. ...
  2. Change the URL. ...
  3. Use 'django-admin-honeypot' ...
  4. Require stronger passwords. ...
  5. Use two-factor authentication. ...
  6. Use the latest version of Django. ...
  7. Never run `DEBUG` in production. ...
  8. Remember your environment.
Feb 4, 2018

What does {% include %} does Django? ›

The include tag allows you to include a template inside the current template. This is useful when you have a block of content that is the same for many pages.

How do I assign a permission to a user? ›

Select a user. In the Permission Set Assignments related list, click Edit Assignments. To assign a permission set, select it under Available Permission Sets and click Add.
The Permission Set Assignments page shows:
  1. Permission sets with no associated license. ...
  2. Permission sets that match the user's license.


1. Python Django Tutorial #12: Django permissions, Django login required mixin | Django blog project
(Red Eyed Coder Club)
2. Restrict urls in function based views | Django | Python
(Django World)
3. 21 | Write custom view decorator & prevent user accessing unauthorized operations | by Hardik Patel
(Hardik Patel)
4. Django Tutorial #24 - Requiring Login
(The Net Ninja)
5. How to Deny Anonymous Users Access to Your Website (Django Tutorial) | Part 24
(Max Goodridge)
6. Python Functions, Decorators, Django custom login required
Top Articles
Latest Posts
Article information

Author: Delena Feil

Last Updated: 10/06/2022

Views: 5624

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.