Django rest framework - Field level validation in

2019-07-04 16:22发布

I have a serializer and I'm trying to add field level validation and I need to verify if some charfields of the serialize are empty or not, and if a boolean field is true or false.

I have this serializer but I never return an error even if Ficha_publicada is false

class PublicarSerializer(serializers.Serializer):

    Titulo = serializers.CharField(required=True)
    Ficha_publicada = serializers.BooleanField()

    def validate_Titulo(self, attrs, source):
        value = attrs[source]

        if not Ficha_publicada:
            raise serializers.ValidationError("Ficha no publicada")
        return attrs

    class Meta:
        model = Fichas

3条回答
狗以群分
2楼-- · 2019-07-04 16:50

use attrs['Ficha_publicada'] :

if not attrs['Ficha_publicada']:
    raise serializers.ValidationError("Ficha no publicada")
return attrs
查看更多
做自己的国王
3楼-- · 2019-07-04 16:53

For Django 1.8 you need to use a slightly different method signature.

From (<1.8) def validate_Titulo(self, attrs, source):

To (1.8) def validate_Titulo(self, attrs, source=None):

If you do not add the default None to the source argument in Django 1.8 you will get a TypeError exception saying:

validate_Titulo() missing 1 required positional argument: 'source'

查看更多
三岁会撩人
4楼-- · 2019-07-04 17:01

And for Django rest framework 3.0 and more recent versions:

def validate_Titulo(self, value):
查看更多
登录 后发表回答