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

Time:10-04

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.

CodePudding user response:

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

CodePudding user response:

Remove default = True. If blank = True then default = False, according to the docs.

But also, null = True means that the value will be required in forms. So removing null = True is also part of the solution.

Try this:

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

Heres a useful answer on the difference between null and blank, too. Its worth the read.

CodePudding user response:

Can you try passing this request

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

If you ware passing empty string then at the end it is string so it will raise ValidationError, also you are using modelserializer so by default it will validate against the type of model field. blank=True will not mean anything with integer.

  • Related