Thứ Bảy, 2 tháng 3, 2019

How to add custom permissions in Django?

Extra permissions to enter into the permissions table when creating this object. Add, change, delete, and view permissions are automatically created for each model. This example specifies an extra permission, can_deliver_pizzas:

# permissions = (((permission_code,  human_readable_permission_name)))
permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)

This is a list or tuple of 2-tuples in the format (permission_code, human_readable_permission_name).

Declare custom permissions example:

# models.py
from django.db import models


class Pizza(models.Model):  
    name = models.CharField(max_length=128)  
    description = models.TextField()  
    
    class Meta:  
        app_label = 'pizza'
        permissions = ((  
            'can_deliver_pizzas', pgettext_lazy('Permission description',  
			  'Can deliver pizzas')),)

Use Permission Decorator at views.py

#views.py
# Use decorator require permission on Django
from django.contrib.auth.decorators import permission_required

@permission_required('product.manage_products')
def product_list(request):
	pass

Easy with Group & Permission in Django

# tests.py
from django.test import TestCase
from django.contrib.auth.models import User, Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import get_user_model


# Create your tests here.
class DjangoGroupPermissionTests(TestCase):

    def setUp(self):
        self.create_user(username='hulk', password='hulk')
        self.create_user(username='captain', password='captain')

    def test_check_permission_on_user_use_group(self):
        hulk = User.objects.get(username='hulk')
        captain = User.objects.get(username='captain')

        leader = self.create_group('Leader')
        member = self.create_group('Member')

        avenger = ContentType.objects.get(app_label='admin', model='logentry')

        can_kick_member = self.create_permission(code_name='kick_member', name='Kick member', content_type=avenger)
        can_view_normal_folder = self.create_permission(code_name='can_view_normal_folder',
                                                        name='can_view_normal_folder', content_type=avenger)
        can_view_important_folder = self.create_permission(code_name='can_view_important_folder',
                                                           name='can_view_important_folder', content_type=avenger)

        # assign permissions to group
        leader.permissions.set([can_kick_member, can_view_important_folder, can_view_normal_folder])
        leader.save()

        member.permissions.add(can_view_normal_folder)
        member.save()

        # assign group to user
        hulk.groups.add(member)
        captain.groups.add(leader)

        self.assertTrue(hulk.has_perm('admin.can_view_normal_folder'))
        self.assertFalse(hulk.has_perm('admin.can_view_important_folder'))
        self.assertTrue(captain.has_perm('admin.can_view_important_folder'))
        self.assertTrue(captain.has_perm('admin.can_view_normal_folder'))
        self.assertTrue(captain.has_perm('admin.kick_member'))

    def create_group(self, name):
        group = Group.objects.create(name=name)
        group.save()
        return group

    def create_permission(self, code_name, name, content_type):
        permission = Permission.objects.create(codename=code_name, name=name, content_type=content_type)
        permission.save()
        return permission

    def create_user(self, username, password):
        user = get_user_model().objects.create_user(
            username, f'{username}@gmail.com', password)
        user.save()
        return user

enter image description here


Reactions: