Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Empty Fields

Tags:

rest

django

Is there a way to allow for empty fields within the Django REST serilaizer for Boolean and Int fields.

class InputAttributes(serializers.Serializer):
    make = serializers.BooleanField(required=False)
    speed = serializers.IntegerField(required=False)
    color = serializers.CharField(required=False,allow_blank=True)

I can use the allow_blank for CharFields but not for the others. Based on the above I get,

A valid integer is required

Any ideas ?

like image 707
felix001 Avatar asked May 27 '15 09:05

felix001


2 Answers

"Django REST Framework serializer field required=false" might help you.

Source: "BooleanField"

BooleanField

A boolean representation.

When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to False, even if it has a default=True option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.

Corresponds to django.db.models.fields.BooleanField.

Signature: BooleanField()

NullBooleanField

A boolean representation that also accepts None as a valid value.

Signature: NullBooleanField()

Corresponds to django.db.models.fields.NullBooleanField.

like image 92
chandu Avatar answered Nov 15 '22 11:11

chandu


If you're finding this question because you actually want your BooleanField to send/receive null as a valid value because you've defined

null=True, default=None

in your model's BooleanField, then define the field in your serializer like this:

myBoolField = serializers.BooleanField(allow_null=True, default=None)

I thought that was what NullBooleanField did at first but it doesn't, I don't see what it's supposed to do really.

like image 31
Sebastián Vansteenkiste Avatar answered Nov 15 '22 12:11

Sebastián Vansteenkiste