2
votes

Rest Framework Django - Disable field to accept null values

How can I configure for the serialized Model to accept blank fields?

Warning

{"Operacao": ["This field can not be blank."]}

Model

class SEF(models.Model):
    operacao = models.CharField(max_length=10, null=True)
    documento = models.CharField(max_length=50, null=True)
    user = models.ForeignKey(User)

Serializer

class SEFCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = SEF
        fields = ('operacao', 'documento', 'user')

View

sef_create = SEFCreateSerializer(data=data, many=True)
        if sef_create.is_valid():
            sef_create.save()
            salvo = HTTP_200_OK
        else:
            salvo = sef_create.errors
3

3 Answers

6
votes

Include allow_blank=True in the field definition as this:

operacao = serializers.CharField(allow_blank=True, allow_null=True)
4
votes
class SEFCreateSerializer(ModelSerializer):

    class Meta:
        model = SEF
        fields = ('operacao', 'documento', 'user')
        extra_kwargs = {'operacao': {'required': False}} 
2
votes

You can set default value like

operacao = models.CharField(max_length=10, default=0)

if you specify a field in model like this it will take default value as 0 if nothing is present.

or in serializer

operacao = serializers.CharField(allow_null = True)