Home > Net >  Django Rest Framework: validate HiddenField CurrentUserDefault property
Django Rest Framework: validate HiddenField CurrentUserDefault property

Time:12-11

I am using DRF to create an API in a single page application. I have a customer user class to which I have only added a is_manager flag and a managerEntity model where users that have the is_manager flag as True can create managerEntities becoming owners of them. The problem is that I can't seem to figure out how to validate the data from the serializer before create method to check whether the is_manager is set or not. If set, the managerEntity should be created, if not, raise an exception.

class DeepmetricsUser(AbstractUser):
    is_manager = models.BooleanField(default=False)

class managerEntity(models.Model):
    id              = models.AutoField(primary_key=True)
    name            = models.CharField(max_length=200)
    owner           = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    team            = models.ManyToManyField(get_user_model(), blank=True)

views.py

class managersEntityViewSet(viewsets.ModelViewSet):

    queryset = managerEntity.objects.all()
    serializer_class = managerEntityModelSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return self.queryset.filter(Q(owner = self.request.user) | Q(team=self.request.user.id))


    def create(self, request, *args, **kwargs):
        serializer = managerEntitySerializer(data=request.data, context={"request": self.request})
        serializer.is_valid(raise_exception=True)
        res = serializer.save()
        data = managerEntityModelSerializer(res).data
        return Response(data, status=status.HTTP_201_CREATED)

serializer.py

class managerEntitySerializer(serializers.Serializer):
    name    = serializers.CharField(max_length=255)
    owner   = serializers.HiddenField(default=serializers.CurrentUserDefault())
        
    def create(self, data):
        res = managerEntity.objects.create(**data)
        return res

CodePudding user response:

You need to override the validate method in Serializer

def validate(self, attrs):
   if not self.context["request"].user.is_manager:
      serializers.ValidationError("Validation error")
   return attrs
  • Related