Hendersoncodes
Hendersoncodes

Reputation: 3

Django REST Framework field serializer validation is not being called

After some hours of research, I still can't find the answer to the issue I am facing.

I am trying to add some simple validation to a field in one of my models.

In serializers.py:

class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = '__all__'

    def validate_name(self, value):
        """
        Check that the brand name has at least 20 characters
        """
        if len(value) < 20:
            raise serializers.ValidationError(
                "The name of the brand should be longer than 20 characters")
        return value

I am using function based views:

@api_view(['POST'])
def brandCreate(request):
    data = request.data
    try:
        brand = Brand.objects.create(
            name=data['name'],
        )
        serializer = BrandSerializer(brand, many=False)
        return Response(serializer.data)
    except:
        message = {'detail': 'Brand is not created'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)

And this is my model:

class Brand(models.Model):
    name = models.CharField(max_length=80)
    logo = models.ImageField(null=True, blank=True)

    def __str__(self):
        return str(self.name)

After sending a POST request with postman, the record is successfully created, even though the name is shorter than 20 characters!

Any hints on what I am missing here? Thank you!

Upvotes: 0

Views: 1101

Answers (1)

Guillaume
Guillaume

Reputation: 2006

You're not using it correctly. You need to call is_valid method.

@api_view(['POST'])
def brandCreate(request):
    data = request.data
    serializer = BrandSerializer(data=data)
    if serializer.is_valid():
        serialiazer.save()
        return Response(serializer.data)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Upvotes: 3

Related Questions