9

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 ?

felix001
  • 15,341
  • 32
  • 94
  • 121
  • possible duplicate of [How to distinguish field that requires null=True when blank=True is set in Django models?](http://stackoverflow.com/questions/1005187/how-to-distinguish-field-that-requires-null-true-when-blank-true-is-set-in-djang) – AncientSwordRage May 27 '15 at 09:03

3 Answers3

2

"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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
chandu
  • 1,053
  • 9
  • 18
  • 1
    this may explain more as well. https://github.com/tomchristie/django-rest-framework/commit/28ff6fb1ec02b7a04c4a0db54885f3735b6dd43f – Chris Hawkes May 27 '15 at 12:52
1

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Sebastián Vansteenkiste
  • 2,234
  • 1
  • 19
  • 29
-6
color = serializers.CharField(null=True,Blank=True)
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • 2
    Please read "[Writing The Perfect Question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)". Formatting is important on SO; Help is available to show how to use it when editing your text. "[How do I format my posts...](https://stackoverflow.com/help/formatting)" will help too. Also, please explain why this should be the selected solution, and how it works; The goal is to educate, not just toss out code. – the Tin Man May 11 '20 at 04:56