I have already asked this question and it can be a song but I hope someone will help me, I am currently doing a project with django restframework, in which I am going to have two groups (Teachers, Students, School) and these already have their permissions assigned in django admin
How do I use group permissions in django rest-framework.
I leave part of my code Modelo.py
class MyUser(AbstractUser):
P_LIST = ((1,'Tourist'),(2,'Enterprise'),(3,'Other'))
Profile = models.IntegerField(choices = P_LIST, default = 1)
class BaseModel(models.Model):
create = models.DateField(auto_now_add = True, null = False, blank = False)
update = models.DateField(auto_now = True, null = False, blank = False)
class Meta:
abstract = True
class CatLanguage(BaseModel):
idLanguage = models.AutoField(primary_key = True)
Name = models.CharField(max_length = 50, null = False, blank = False)
Acronym = models.CharField(max_length = 5, null = False)
Note = models.CharField(max_length = 2500, null = True, blank = True)
def __str__(self):
return self.Name
class TblGallery(BaseModel):
IdGallery = models.AutoField(primary_key = True)
Location = models.CharField(max_length = 1500, null = False)
def __str__(self):
return str(self.IdGallery)
Serializer and Viesets:
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser
from django.views import generic
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework import serializers, viewsets, permissions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
#Models Import
from Base.models import *
from Base.permissions import *
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
"""
class MyUserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MyUser
fields = ('id','Profile','email', 'first_name', 'last_name', 'password', 'is_superuser')
class MyUserViewSet(viewsets.ModelViewSet):
serializer_class = MyUserSerializer
queryset = MyUser.objects.all()
def get_serializer_class(self):
return MyUserSerializer
"""
#Serialiazers
class LanguageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = CatLanguage
fields = ['idLanguage','Name','Acronym','Note','create','update']
class GallerySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = TblGallery
fields = ('IdGallery','Location','create','update')
class GalleryDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = TblGalleryDetail
fields = ('IdGalleryDetail','IdGallery','IdLanguage','Name','Description')
#--------------- ViewSets ----------------------------------------------
class LanguageViewSet(viewsets.ModelViewSet):
#authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication]
authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)
permissions_classes = [UserPermission]
queryset = CatLanguage.objects.all()
serializers_class = LanguageSerializer
def get_serializer_class(self):
return LanguageSerializer
#---------------
class GalleryViewSet(viewsets.ModelViewSet):
serializers_class = GallerySerializer
queryset = TblGallery.objects.all()
def get_serializer_class(self):
return GallerySerializer
class GalleryDetailViewSet(viewsets.ModelViewSet):
serializers_class = GalleryDetailSerializer
queryset = TblGalleryDetail.objects.all()
def get_serializer_class(self):
return GalleryDetailSerializer
I leave the Permissions.py there are class rods that and try, also none of them is to search for permissions and groups.
from rest_framework.exceptions import PermissionDenied, NotAuthenticated
from rest_framework import permissions
from rest_framework.permissions import BasePermission
from django.contrib.auth.models import User
#---
from django.contrib.auth.decorators import user_passes_test
def group_required(*group_names):
"""Requires user membership in at least one of the groups passed in."""
def in_groups(u):
if u.is_authenticated():
if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:
return True
return False
return user_passes_test(in_groups, login_url='403')
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS','POST']
class Profile(BasePermission):
def has_object_permission(self, request, view, obj):
"""
Return True if the user is the owner of the ..
"""
if request.method in SAFE_METHODS:
return False
elif request.method == 'PUT' or request.method =='POST':
if request.user.Profile == 1:
return True
return False
class UserPermission(permissions.BasePermission):
def has_permission(self, request, view):
if view.action == 'list':
return request.user.is_authenticated() and request.user.is_admin
elif view.action == 'create':
return True
elif view.action in ['retrieve', 'update', 'partial_update', 'destroy']:
return True
else:
return False
def has_object_permission(self, request, view, obj):
if view.action == 'retrieve':
return request.user.is_authenticated() and (obj == request.user or request.user.is_admin)
elif view.action in ['update', 'partial_update']:
return request.user.is_authenticated() and (obj == request.user or request.user.is_admin)
elif view.action == 'destroy':
return request.user.is_authenticated() and request.user.Profile == 1
else:
return False
In the end, I repeat what I try to do is read the Group and individual permissions of a user and based on that allow him to read, create, update and delete records.
Thanks in advance
Try this:
Example for the group
Estudiante
: