The Wayback Machine - https://web.archive.org/web/20240927174727/https://www.geeksforgeeks.org/python-user-groups-custom-permissions-django/
Open In App

Python | User groups with Custom permissions in Django

Last Updated : 31 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let’s consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products.

Let’s see the different packages available on tour booking service :

  1. Starter plan : In this package, subscriber will get the facility of non-AC bus travel and 1-day stay in a non-AC room only. Let’s say the trip is from Delhi to Haridwar(a religious place in Uttarakhand).
  2. Golden Plan : It will be somewhat costly than the Starter Plan. In this plan, subscriber will be given 2-day stay in a non-AC room, travelling in a AC bus and the trip will be from Delhi to Haridwar, Rishikesh and Mussoorie.
  3. Diamond Plan: This is the most costly plan, in which subscriber will be provided 3-day plan with AC bus and AC room stay, along with the trip to Haridwar, Rishikesh and Mussoorie and also trip to the Water Park.

Our main objective is to design and write code for the back-end in a very efficient way(following the DRY Principle).
There are multiple methods of implementing this in Django but the most suitable and efficient method is Grouping the Users and defining the permissions of these groups. User of that particular group will automatically inherit the permission of that particular group. Let’s define the User model first :

Create a Django application users. In models.py file, under ‘users’ app directory, write this code.  

Python3




# importing necessary django classes
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
from django.db import models
 
# User class
class User(AbstractUser):
 
    # Define the extra fields
    # related to User here
    first_name = models.CharField(_('First Name of User'),
                            blank = True, max_length = 20)
                             
    last_name = models.CharField(_('Last Name of User'),
                            blank = True, max_length = 20)
                             
# More User fields according to need
 
    # define the custom permissions
    # related to User.
    class Meta:
         
        permissions = (
            ("can_go_in_non_ac_bus", "To provide non-AC Bus facility"),
            ("can_go_in_ac_bus", "To provide AC-Bus facility"),
            ("can_stay_ac-room", "To provide staying at AC room"),
            ("can_stay_ac-room", "To provide staying at Non-AC room"),
            ("can_go_dehradoon", "Trip to Dehradoon"),
            ("can_go_mussoorie", "Trip to Mussoorie"),
            ("can_go_haridwaar", "Trip to Haridwaar"),
            ("can_go_rishikesh", "Trip to Rishikesh"),
 
# Add other custom permissions according to need.


  
After migrating the models written above, we have two option for making the group.

  1. Django Admin Panel : In Admin Panel you will see Group in bold letter, Click on that and make 3-different group named level0, level1, level3 . Also, define the custom permissions according to the need.
  2. By Programmatically creating a group with permissions: Open python shell using python manage.py shell.

Python3




# importing group class from django
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
 
# import User model
from users.models import User
 
new_group, created = Group.objects.get_or_create(name ='new_group')
 
# Code to add permission to group
ct = ContentType.objects.get_for_model(User)
 
# If I want to add 'Can go Haridwar' permission to level0 ?
permission = Permission.objects.create(codename ='can_go_haridwar',
                                        name ='Can go to Haridwar',
                                                content_type = ct)
new_group.permissions.add(permission)


 
We will set different set of permissions in the same way to all the three groups. Until then, we have made groups and linked it with custom permissions.

Now, check that a particular user is accessing the appropriate functionality like, put a limit that level0 does not access the functionalities of level1 users or level2 user and so on. To do this, check the permission on every view function made.
To be very careful here, for the function based view we will simply use the custom decorator. 

For example :  

Python




@group_required('level0')
def my_view(request):
    ...


For more details, refer this.
Things get a bit complex when we talk about class-based views, we can not simply just add a decorator function, but we have to make a permission-mixing class.

For example :  

Python




class GroupRequiredMixin(object):
    ...............
    ....Class Definition.....
 
 
class DemoView(GroupRequiredMixin, View):
  group_required = [u'admin', u'manager']
   
  # View code...


For more details, refer this.

References : 
1. https://docs.djangoproject.com/en/1.11/topics/class-based-views/mixins/ 
2. http://bradmontgomery.blogspot.in/2009/04/restricting-access-by-group-in-django.html 
3. https://simpleisbetterthancomplex.com/2015/12/07/working-with-django-view-decorators.html 
4. https://micropyramid.com/blog/custom-decorators-to-check-user-roles-and-permissions-in-django/
 



Previous Article
Next Article

Similar Reads

Creating Custom Decorator in Django for different permissions
Decorators are incredibly helpful tools that allow you to dynamically change the functionality of a function, method, or class without having to utilize subclasses directly or modify the function's source code. The decorator's login_required, require HTTP methods, require POST, and others are needed when working with Django views. But there are als
9 min read
Customizing Object Level Permissions - Django REST Framework
In this article, we will discuss how to customize Object Level Permissions in Django REST Framework. To customize permission classes in Django REST Framework, we should inherit the rest_framework.permissions.BasePermission class and implement either or both of the following methods: .has_permission(self, request, view).has_object_permission(self, r
5 min read
How To Use Django Permissions Without Defining a Content Type or Model
Django's permissions framework is a powerful feature that allows developers to control access to different parts of their applications. Typically, permissions are tied to models through Django's built-in content type system. However, there are scenarios where we may want to implement custom permissions that aren't directly linked to a specific mode
5 min read
Creating custom user model API extending AbstractUser in Django
Every new Django project should use a custom user model. The official Django documentation says it is “highly recommended” but I’ll go a step further and say without hesitation: You are straight up crazy not to use a custom user model up front. Why do u need a custom user model in Django? When you start your project with a custom user model, stop t
4 min read
Grant MySQL table and column permissions using Python
MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such a
2 min read
Granting Permissions to Roles in Cassandra
In this article, we are going to discuss how we can granting permission to roles in Cassandra. First, we will create a new role and show how it can access the database. Creating a new role: In this step, we are going to create a new role such that user_access is a new role and want to access the database. To create a new role using the following cq
2 min read
How to Solve "File writing permissions blocked by the EPERM" issue in Node.js ?
Encountering the “EPERM: operation not permitted” error in Node.js when trying to write to a file is a common issue that often indicates insufficient permissions. This error can be frustrating, but understanding its causes and solutions can help you overcome it efficiently. This article will guide you through the various strategies to resolve the “
4 min read
How to Set File Permissions in Linux?
Setting file permissions in Linux is a fundamental task for managing access to files and directories. Proper file permissions ensure that only authorized users can read, write, or execute files, enhancing the security and functionality of your system. In this guide, we will explain how to set file permissions in Linux using various commands and tec
8 min read
How to set up file permissions for Laravel?
Setting up proper file permissions for a Laravel application is crucial for its security and functionality. Laravel, a popular PHP framework, often requires the webserver to have the ability to read and write to specific directories. Incorrect permissions can lead to various issues, such as the inability to write logs or cache data, which can cause
4 min read
Permissions And Roles in GitLab
One of the important settings of GitLab is its permission and role system, which decides what users can and cannot do within a project or group. Understanding GitLab’s permission model is important for managing access, collaboration, and security within your teams and projects. This article will explore the various permissions and roles available i
5 min read
How to Change File Permissions in WordPress?
WordPress is a CMS or content management system that is very popular and used because of its features to create and manage websites such as blogs, e-commerce platforms, etc without having to code the website, it is important to understand the file permissions and how we can control it for making sure that the website is secure. These are the follow
5 min read
Python Django Handling Custom Error Page
To handle error reporting in Django, you can utilize Django's built-in form validation mechanisms and Django's error handling capabilities. In this article, I'll demonstrate how to implement error handling. If there are errors in the form submission, the user will be notified of the errors. Required Modules Install DjangoCreate Virtual Env Python D
4 min read
Creating multiple user types and using proxy models in Python Django
In this article, we will understand the concept of the proxy model and the implementation of multiple user types depending on the requirements of your application in Django. What is the Proxy model in Django? An inherited proxy model can have a few extra functionalities, methods, and different behaviors than the parent model as defined by the creat
9 min read
How to add custom styles and ways to add custom styles in Tailwind-CSS ?
Tailwind is a popular CSS framework that makes your User Interface design making the process easier. It provides low-level classes and those classes combine to create styles for various components. Tailwind-CSS comes with a bunch of predefined styling but as a developer, we need more custom styling and the styles offered by tailwind are not enough
3 min read
Creating custom user model using AbstractUser in django_Restframework
Every new Django project should use a custom user model. The official Django documentation says it is “highly recommended” but I’ll go a step further and say without hesitation: You are straight up crazy not to use a custom user model up front. Why do u need a custom user model in Django? When you start your project with a custom user model, stop t
4 min read
Custom C++ User Snippet in Visual Studio Code
Snippets are the small portion of re-usable code wrapped in some prefix word, It allows programmers to bind a particular block of code in a single prefix keyword. Visual Studio Code is a Lightweight and powerful source code editor available in Windows, Linux, and macOS, It comes with many built-in snippets for the loops, control statements, and som
3 min read
Implementation of Tic-Tac-Toe for 2 person game (User vs. User)
For 1-Person game (User vs. CPU), please refer Implementation of Tic-Tac-Toe game Rules of the Game The game is to be played between two people (in this program between HUMAN to HUMAN).First the game will take the names of the two players as input.One of the player chooses ‘O’ and the other ‘X’ to mark their respective cells.There would be a game t
9 min read
User to User private Chat App using ReactJS and Firebase | Without socket programming
This article covers how to make a User to User private Chat App using React JS and Firebase (without socket programming). React is a JavaScript framework provided by Facebook and is used to build fully-featured web applications. We will be following the below steps for creating our application: npx create-react-app chat-appcd chat-appNow install al
10 min read
Custom Field Validations in Django Models
This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the model itself so that you need not manipulate it elsewhere. Thes
3 min read
Django form field custom widgets
A widget is Django’s representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. Whenever you specify a field on a form, Django will use a default widget that is appropriate to the type of data that is to be displayed. To find which widg
3 min read
How to create Custom Template Tags in Django ?
Django offers a variety of built-in template tags such as {% if %} or {% block %}. However, Django also allows you to create your own template tags to perform custom actions. The power of custom template tags is that you can process any data and add it to any template regardless of the view executed. You can perform QuerySets or process any data to
4 min read
How to Integrate Custom Rich Text-Editor in Your Django Website?
In this article, we will implement tinymce text editor in our Django application. What is django-tinymce? django-tinymce is a Django application that contains a widget to render a form field as a TinyMCE editor. Features :- Use as a form widget or with a view.Enhanced support for content languages.Integration with the TinyMCE spellchecker.Enables p
3 min read
Custom Template Filters in Django
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. What is filters in Django template language (DTL) ? Before move to see the ho
2 min read
Custom Field Validations in Django Forms
This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the form itself so that you need not manipulate it elsewhere. What
2 min read
Built in & Custom Model Managers in Django
Django manager is a class that acts as an interface through which Django models interact with databases. Every model has at least one manager object. It has a lot of methods, attributes to ease working with databases. In fact, many beginner-level Django developers do not know that they use the Manager class object to extract or create desired model
6 min read
How to return custom JSON in Django REST Framework ?
In this article, we will create class-based views and combine this with the serializer class to return JSON representation for each HTTP request. For our class-based views, we will make use of a set of generic views, which help to achieve minimum lines code. Generic Classes and ViewsetsHTTP requests to interact with relationship resourcesGeneric Cl
9 min read
Custom Django Management Commands
Prerequisites: Django Introduction and Installation Manage.py in Django is a command-line utility that works similar to the django-admin command. The difference is that it points towards the project's settings.py file. This manage.py utility provides various commands that you must have while working with Django. Some of the most commonly used comma
4 min read
How to Write Custom Lookups in Django?
Custom lookups allow you to define custom filters that can be used in database queries. By default, Django provides a set of built-in lookups such as exact, icontains, gt, lt, etc., which allow you to perform common filtering operations on query sets. However, sometimes you may need to perform more complex or specialized filtering that isn't covere
3 min read
Making a Django Admin Field Non-Required Without Custom Form Creation
The Django admin interface is a great tool for managing data in your Django application. Sometimes, you may need to make some fields optional in the admin panel, meaning these fields shouldn't be required when creating or updating records. Typically, this is done by creating a custom form. However, there is a simpler way to achieve this directly in
2 min read
Running Custom Django manage.py Commands in Tests
Django's manage.py commands are powerful tools for performing various administrative tasks. Sometimes, you might want to call these custom commands directly from your test suite to test their functionality or to set up the environment for your tests. In this article, we will walk through the process of creating a Django project, writing a custom ma
2 min read