I am working on DRF and using viewsets for creating APIs. Here I am having one problem:
Suppose, I have two buttons in a form i.e. Employee and Manager. If the user clicked on Employee, then it has access to only GET request and if he clicked on Manager, then it has POST, PUT, PATCH permissions.
models.py
class Employee(models.Model):
emp_id = models.AutoField(primary_key=True)
emp_name = models.CharField(max_length=30)
email = models.EmailField(max_length=254, unique=True)
position = models.CharField(max_length=30)
team = models.CharField(max_length=30)
phone = models.CharField(max_length=20, unique=True)
viewsets.py
class EmpViewSet(viewsets.ModelViewSet):
serializer_class = EmployeeSerializer
queryset = Employee.objects.all()
permission_classes = [OfficeEngineerPermission]
serializers.py
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = '__all__'
I tried to write custom permission but it doesn't work.
custom_permiss.py
SAFE_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'HEADER', 'OPTIONS']
class OfficeEngineerPermission(BasePermission):
def has_permission(self, request, view):
if (request.method in SAFE_METHODS and request.user == 'OfficeEngineer'):
return True
return Response({'message':'This is not allowed'})
I read all things but getting stuck. Please suggest!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…