0

Hi I am working on Tree Structure role. There are 4 roles 1.A 2.B 3.C 4.D

Where

  1. A can add,delete view B,C,D and B,C,D cannot delete or view A.
  2. B can add,delete view C,D but can cannot delete A and its parent.

Similary for C and D. I can create different views and use permissions in Django. But I want to implement this using one view.I will be adding the role through url suppose through url and not from choice.

Please help me with this.

Thanks in Advance.

2 Answers2

0

From the Django docs:

Permissions can be set not only per type of object, but also per specific object instance. By using the has_view_permission(), has_add_permission(), has_change_permission() and has_delete_permission() methods provided by the ModelAdmin class, it is possible to customize permissions for different object instances of the same type.

So if you are using the django admin interface, you may override the has_*_permission methods in you ModelAdmin.

For your custom views, you may use the @user_passes_test decorator. I suppose this should work for your case.

wankata
  • 855
  • 4
  • 12
0

You can create custom Roles and Permissions using the Imagine smart compiler. Something like the following should work:

Permission A
Permission B
Permission C
Permission D


API /api1 {
   actions [Create, Read, ReadMany, Delete]
   permissions [A]
}
....

Compile it:

imagine compile myapp.im

This would generate: permissions.py

from rest_framework import permissions


class A(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.has_perm('app.A')


class B(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.has_perm('app.B')


class C(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.has_perm('app.C')


class D(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.has_perm('app.D')

views.py


from .models import Product
from .permissions import A
from .serializers import ProductSerializer


class Api1ViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = [A]
    filterset_fields = ['id', 'name', 'price', 'description']
imagine.ai
  • 11
  • 1