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

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

Built-In Login and Logout Authentication System in Django

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

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.

  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.

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.


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

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


How to restrict user login 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.

What is login_required decorator Django? ›

The login_required decorator

login_required() does the following: If the user isn't logged in, redirect to settings.LOGIN_URL , passing the current absolute path in the query string. Example: /accounts/login/?next=/polls/3/ . If the user is logged in, execute the view normally.

How to disable Django admin login? ›

To disable admin just remove url(r'^admin/', admin. site. urls), from your main . Another things to clean are 'django.

What is the function of login_required decorator? ›

The login_required decorator is a decorator that can be used in Django that requires a view to have the user logged in. If the user is not logged in, the user will automatically be redirected to the login page (so that the person can log in). The login_required decorator, thus, forces a user to log in.

How to import login required decorator in Django? ›

from django.contrib.auth.decorators import login_required @login_required(login_url='/accounts/login/') def my_view(request): ... Note that if you don't specify the login_url parameter, you'll need to ensure that the settings.LOGIN_URL and your login view are properly associated.

How do I restrict user login? ›

Option C: Configure "Deny logon locally" user right on the local computer/s
  1. Go to "Start" -> "Run".
  2. Write "Gpedit.msc"
  3. Enable "Deny logon locally" user right to the source domain user accounts. Note. ...
  4. Run Gpupdate /force on the local computer.
Feb 23, 2023

How do I restrict user access? ›

Using encryption software is the most effective way of limiting who can view or interact with private information without impacting productivity. Instead of locking down the area where data is stored, making it harder to access, this process protects the information itself.

How does login_required work in Django? ›

Django's login_required function is used to secure views in your web applications by forcing the client to authenticate with a valid logged-in User.

How to use Django permissions? ›

By default, Django automatically gives add, change, and delete permissions to all models, which allow users with the permissions to perform the associated actions via the admin site. You can define your own permissions to models and grant them to specific users.

What is @wraps decorator in Python? ›

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.

How to protect Django admin? ›

How to secure Django Admin
  1. Use SSL. We suggest enabling SSL for the website so that the site is 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 the environment.
Jan 3, 2021

How to remove Django authentication? ›

Just need to apply django rest framework AllowAny permission to the specific method or class. You can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit. Save this answer.

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

What is login required decorator in Python? ›

The decorator @login_required is used to secure the bookapi/books/:bookid route in a the Flask application. It enforces the rule that the client has to either authenticate with a valid logged-in user or have an existing token.

What does the @property decorator do? ›

The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.

Why use decorator instead of function? ›

By using a decorator, you can add extra functionality without changing the original function, making your code cleaner and more organized.

How to set custom 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.

How does Django handle user authentication and authorization in Python? ›

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.

How to use custom authentication in Django? ›

When you need to refer to the custom user from other parts of your code, you can do that in any of the following ways:
  1. from users import User.
  2. from customuser. settings import AUTH_USER_MODEL.
  3. use the get_user_model() method from django. contrib. auth.

How user's access can be restricted using role based login? ›

By adding a user to a role group, the user has access to all the roles in that group. If they are removed, access becomes restricted. Users may also be assigned to multiple groups in the event they need temporary access to certain data or programs and then removed once the project is complete.

How do I restrict users from login on multiple devices? ›

Limit Number of Devices a User can Access at the Same Time Follow
  1. Select Settings> Security.
  2. Under "Account Security," select the checkbox for "Don't allow attendees to be logged into more than one device at a time." and Save.

Which command can you use to lock a user account to prevent login? ›

Locking the user account

To lock a user account use the command usermod -L or passwd -l. Both the commands adds an exclamation mark (“!”) in the second field of the file /etc/shadow.It has to be executed by either boby/privilaged user. It will deny any access which would be done directly using su or with ssh.

How do I manage user permissions in access? ›

On the Database Tools tab, in the Administer group, click Users and Permissions. Click one of the following commands: User and Group Permissions Use this to grant or revoke user or group permissions, or to change the owner of database objects.

What is an example of a user access restriction? ›

For example, a user can access a normal address, but cannot see a secured address. Furthermore, the restrictions indicate if the user may read, create, update and / or delete data.

Can I use a permission set to reduce access to a user? ›

Permission Set Control

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.

How to use login view in Django? ›

Django's LoginView allows you to display the login form and process the login action. We'll use the LoginView class to create a login page for the Todo App.
  1. Use the LoginView class to create a login page.
  2. Use the LogoutView class to log a user out.
  3. Use the LoginRequiredMixin class to protect a page.

How to use decorator in Django? ›

To add a decorator function to every instance of a class-based view, you need to decorate the class definition itself. To do this, you pass the name of the method to be decorated as the keyword argument name: from . decorators import authentication_not_required from django.

How to redirect to login page in Django? ›

Add @login_required decorator to the view that loads the dashboard page. If a user without authentication tries to access dashboard page, he will be redirected to login page and on successfull login redirected back to dashboard page.

How does Django admin login work? ›

To login to the site, open the /admin URL (e.g. ) and enter your new superuser userid and password credentials (you'll be redirected to the login page, and then back to the /admin URL after you've entered your details).

How to set admin user in Django? ›

Creating an admin user
  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.

What are the two types of decorators in Python? ›

In fact, there are two types of decorators in Python — class decorators and function decorators — but I will focus on function decorators here.

What is difference between wrapper and decorator? ›

“Wrapper” is the alternative nickname for the Decorator pattern that clearly expresses the main idea of the pattern. A wrapper is an object that can be linked with some target object. The wrapper contains the same set of methods as the target and delegates to it all requests it receives.

Is wrapper the same as decorator? ›

Function wrappers are useful tools for modifying the behavior of functions. In Python, they're called decorators. Decorators allow us to extend the behavior of a function or a class without changing the original implementation of the wrapped function.

How to handle passwords in Django? ›

For storing passwords, Django will use the first hasher in PASSWORD_HASHERS . To store new passwords with a different algorithm, put your preferred algorithm first in PASSWORD_HASHERS . For verifying passwords, Django will find the hasher in the list that matches the algorithm name in the stored password.

How to override Django admin? ›

To override these templates, you will need to have an admin folder in your templates folder. If you do not have a templates folder, you can create it in the main project folder. To do so, you will have to change the project's . Find the TEMPLATES section and modify accordingly.

How to protect Django code? ›

Use a .

gitignore file tells git what files and directories to ignore. Git will automatically ignore any file or directory put in this file to protect sensitive information. Create . gitignore files at the root of your GitHub repository before you git-clone it to VSCode.

What is alternative for Django authentication? ›

JSON Web Token, Auth0, Keycloak, Amazon Cognito, and OAuth2 are the most popular alternatives and competitors to Django REST framework JWT.

Does Django have user authentication? ›

Django comes with a user authentication system. It handles user accounts, groups, permissions and cookie-based user sessions. This section of the documentation explains how the default implementation works out of the box, as well as how to extend and customize it to suit your project's needs.

How to remove required attribute in Django forms? ›

Use form = GroupForm(use_required_attribute=False) when you initialize your form in your .

How to create a login function in Django? ›

To write your login function, add an if/else statement that uses the Django function authenticate() . This function is used to verify user credentials (username and password) and return the correct User object stored in the backend.

How to create multiple user login in Django? ›

Creating More than one user SignUp
  1. Step1:- Create django project folder. Create django project folder. ...
  2. Step2:- Add files and folder in django project folder. We need to create a template folder in the django folder and a file in the app folder. ...
  3. Step3:- Create more than one user.
Jun 11, 2021

How do I pass login credentials in Python script? ›

Get User Name And Password At Runtime Using Python
  1. pip install getpass. Python. Copy.
  2. userName = getpass. getuser() Python. Copy.
  3. userName= input('Enter user name: ') Python. Copy.
  4. password = getpass. getpass() Python. Copy.
Jun 9, 2022

Why we use decorators in Django? ›

Decorators are a way to restrict access to views based on the request method or control caching behaviour. This is particularly useful when you want to separate logged-in users from unauthenticated users or create an admin page that only privileged users can access.

What is the @property function in Django? ›

How does the @property decorator work? The @property decorator is a built-in decorator in Python for the property() function. This function returns a special descriptor object which allows direct access to getter, setter, and deleter methods.

What does @property means in Python? ›

Python's property() is the Pythonic way to avoid formal getter and setter methods in your code. This function allows you to turn class attributes into properties or managed attributes. Since property() is a built-in function, you can use it without importing anything.

What is @property in python3? ›

The @property Decorator

In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None) Here, fget is function to get value of the attribute. fset is function to set value of the attribute.

What is the biggest advantage of the decorator in Python? ›

A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.

What are the key advantages of using a decorator? ›

You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.

Can a decorator take two functions? ›

Conceptually, decorators are supposed to alter the functionality of a single function they decorate; a function that sequences two other functions on an equal footing may not make much sense as a decorator.

How to restrict access by user 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.

How do I give permission to a specific user 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 assign custom permissions to a user? ›

  1. From Setup, enter Permission Sets in the Quick Find box, then select Permission Sets.
  2. Select a permission set, or create one.
  3. On the permission set overview page, click Custom Permissions.
  4. Click Edit.
  5. To enable custom permissions, select them from the Available Custom Permissions list and then click Add. ...
  6. Click Save.

What is the difference between authentication and Authorisation in Django? ›

Simply put, authentication is the process of verifying who someone is, whereas authorization is the process of verifying what specific applications, files, and data a user has access to.

Which method of authentication takes credentials in Django? ›

The get_user method takes a user_id – which could be a username, database ID or whatever, but has to be the primary key of your user object – and returns a user object. The authenticate method takes credentials as keyword arguments.

How to create users without setting their password 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. This is explained here. The trick is to use create() instead of create_user(), as discussed here.

How to customize Django login? ›

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 manage users in Django? ›

What You Need to Know to Manage Users in Django Admin
  1. Setup: A Custom User Admin.
  2. Prevent Update of Fields.
  3. Conditionally Prevent Update of Fields.
  4. Prevent Non-Superusers From Granting Superuser Rights.
  5. Grant Permissions Only Using Groups.
  6. Prevent Non-Superusers From Editing Their Own Permissions.
  7. Override Permissions.

How to make username optional Django? ›

auth you can't make the username field optional. You always have to put a value in the database. In order to bypass that, I suggest you generate a value in create_user() for username. You could either use a random value, or create a username from email.

How do I set a user login without a password? ›

Method 1: Enable Windows Auto Login via Netplwiz
  1. Step 1: On your desktop screen, open the Run dialogue box using the "Win + R" key. ...
  2. Step 2: Now select your user account among the users and uncheck the "Users must enter a username and password to use this computer" box and click "Apply" to enable Auto Login Windows 10.
Mar 22, 2023

How to make password field optional in Django? ›

In order to make a field optional, we have to say so explicitly. If we want to make the pub_time field optional, we add blank=True to the model, which tells Django's field validation that pub_time can be empty.

How to make an admin login with 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 to manage login session in Django? ›

To set up a session in Django, we need to add two things in our :
  1. 'django. contrib. sessions. middleware. SessionMiddleware' to MIDDLEWARE.
  2. 'django. contrib. sessions' to INSTALLED_APPS . Run python migrate to populate the table.

How does Django login work? ›

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.

Top Articles
Latest Posts
Article information

Author: Otha Schamberger

Last Updated:

Views: 6160

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.