Table of contents
1.
Introduction
2.
Django User Groups With Custom Permissions
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024

Django User Groups With Custom Permissions

Author Tanay kumar Deo
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Django is one of Python's most popular, trusted, and reliable web development frameworks. With Django, we can quickly create web applications without worrying about installation or dependency problems that we usually find with other frameworks.

Let's consider an education service provider. They work with users with different roles and different plans. There are few services and products which can only be available for a particular role or any subscriber.  For example, students cannot access the teacher’s dashboard or the admin’s dashboard. Let’s understand Django User Groups With Custom Permissions with the help of this example.

This article will learn about implementing these other Django User Groups With Custom Permissions.

Django User Groups With Custom Permissions

Generally, the idea they (education service providers) follow is the level-wise distribution of services. Let's see different types of subscriptions available for users:

  • Starter plan:- In this Subscription (Free) plan, users will get access to different free study plans and courses. They will also get one free test series.
  • Golden Plan:- This plan will be a bit costlier than the previous plan. Users will get access to free and paid study plans and courses. They will get one free test series.
  • Diamond Plan: This plan is the most costly. This plan is the same as the Golden plan, but it has access to all the available test series.

 

We can implement this in multiple ways in Django, but the most efficient and suitable method is to group the users and define custom permissions for these groups. A user of a particular group will automatically inherit the permissions of that specific group. Let's explain our User model first in models.py:

from django.contrib.auth.models import AbstractUser
from django.db import models
 
# User model class
class User(AbstractUser):
    # Define the extra fields 
    first_name = models.CharField(_('First Name of the User'),
                            blank = True, max_length = 20)
             
    last_name = models.CharField(_('Last Name of the User'),
                            blank = True, max_length = 20)
                             
# More User fields according to the needs
     # Define all the custom permissions
    class Meta:     
                    permissions = (
                        ("can_add_new_features", "To add new features"),
                        ("can_add_tutorials", "To add different tutorials"),
                        ("can_add_blogs", "To add blogs"),
                ("can_add_course", "To add different courses"),
                ("can_delete_courses", "To delete different courses"),
                ("can_delete_blogs", "To delete different blogs"),
                ("can_block_users", "Can block different Users"),
You can also try this code with Online Python Compiler
Run Code

 

In the above code, we added the User model class. Now, let's see different Django user groups available:

  • Admin - They have access to all the features available and can also modify the features for different Django user groups.
  • Teacher - They can manage their students, classrooms, study materials, etc.
  • Content Writer - They can manage and write content like tutorials, blogs, etc.
  • Student - Students can access the resources publicly available, and also they have different types of access to the resources based upon their subscription.

 

We have two options for making different Django user groups with custom permissions:

1. Django Admin Panel: In the admin panel, we will find the group option in the bold letter, Click on that and make four different groups named level0 (Admin), level1 (Teacher), level3 (Content Writer), lavel4 (Students). Also, define the Django user groups with custom permissions according to the need.

2. By Programmatically creating groups with permission: Open python shell with Python manage.py shell.

# Importing group class
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
 
# Import model User
from users.models import User

new_group, created = Group.objects.get_or_create(name ='admin_group')
 
# Code to add permission 
ct = ContentType.objects.get_for_model(User)
 
# If we want to add 'Can Add New Features' permission to level0 ?
permission = Permission.objects.create(codename ='can_add_new_features',
                                        name ='Can Add New Features',
                                                content_type = ct)
new_group.permissions.add(permission)
You can also try this code with Online Python Compiler
Run Code

 

We added "Can Add New Features” permission to the admin_group in the above code. We can set different permission sets in the same way for all four groups.

Now, let's check that every user is accessing the appropriate functionality. For example, limit  level4 users from accessing the functionalities of level0 userslevel1 users, or level2 users, etc. To do so, check the permission on every view function.

We will use the custom decorator for the function-based view to be very careful here. For example

@group_required('level0')
def my_view(request):
    ...
You can also try this code with Online Python Compiler
Run Code

 

But in class-based generic views, things get a bit complex. We can not just add the decorator function, but instead, we need to make a permission-mixing class. For example,

class GroupRequiredMixin(object):
    ............
    # Class Definition
 
class DemoView(GroupRequiredMixin, View):
  group_required = [u'admin', u'manager']
  
  # View code
You can also try this code with Online Python Compiler
Run Code

 

For more details, refer to this.

FAQs

  1. Should we use different user models for different Django user roles?
    Although we can use different user models for different user roles, storing user information across multiple models/tables is always a bad idea.
     
  2. What is the difference between AbstractBaseUser and AbstractUser in Django?
    AbstractUser is a complete User model, with fields, like an abstract class to inherit it and add our own profile fields and methods. While AbstractBaseUser only contains the functionality for authentication but no actual fields: we need to supply them in our subclass.

Key Takeaways

In this article, we learned about Django user groups with custom permissions. We discussed an education prodigy service to understand better different user roles and custom permissions in a real-life project. Finally, we implemented different Django user groups with custom permissions.

Don't stop here. Check out the blogs Best Django Books, Top 30 Basic Django Interview Questions: Part 1, and Top 30 Intermediate Django Interview Questions: Part 2.

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass