Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django REST Framework - Integer field will not accept empty response?

The models.py IntegerField is set-up:

class DMCAModel(models.Model):
    tick = models.CharField(max_length=20)
    percent_calc = models.FloatField()
    ratio = models.IntegerField(blank=True, null=True, default=None)   #The problem is here
    created_at = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, related_name='dmca',
                              on_delete=models.CASCADE, null=True)

serilaizers.py

class DMCASerializer(serializers.ModelSerializer):
    class Meta:
        model = DMCAModel
        fields = '__all__'
        # fields = ['id', 'tick', 'percent_calc', 'ratio']
# I have tried removing fields, if I remove 'ratio' then even if I send an input it is ignored.

api.py

class DmcaViewSet(viewsets.ModelViewSet):
    # queryset = DMCAModel.objects.all()
    permission_classes = [
        permissions.IsAuthenticated
    ]

    serializer_class = DMCASerializer

    def get_queryset(self):
        return self.request.user.dmca.all()

    def perform_create(self, serializer):
        # print(self.request.user)
        serializer.save(owner=self.request.user)

When I to make the following POST request from postman:

Authorization: Token xxxxxx
Body JSON:
{
"tick":"XYZ",
"percent_calc":"3",
"ratio":""
}

I get the error:

{ "ratio": [ "A valid integer is required." ] }

I think I have set the properties of the Models field correctly if I understand them correctly: null=True database will set empty to NULL, blank=True form input will be accepted, default=None incase nothing is entered. I have tried to use the properties one by one and see what happens. But can't work out the error.

like image 991
Sid Avatar asked Dec 19 '25 16:12

Sid


1 Answers

Inside your serializer, you can use a CharField for the ratio field if you want to send an empty string and then convert to Int in the validation method.

class DMCASerializer(serializers.ModelSerializer):
     ratio = serializers.CharField(required=False, allow_null=True, allow_blank=True)

     class Meta:
         model = DMCAModel
         fields = '__all__'

     def validate_ratio(self, value):
         if not value:
             return None
         try:
             return int(value)
         except ValueError:
            raise serializers.ValidationError('Valid integer is required')

Also, you need to change serializer_class inside DmcaViewSet from:

serializer_class = DcaSerializer

to

serializer_class = DMCASerializer

When I send an empty string:

enter image description here

When I send an Integer:

enter image description here

like image 137
Milos Bogdanovic Avatar answered Dec 21 '25 05:12

Milos Bogdanovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!