Home > Back-end >  I want to know about using required=False in a DRF Serializer
I want to know about using required=False in a DRF Serializer

Time:10-15

I have a Serializer (not a model serializer)

class DummySerializer(serializers.Serializer):
    clas = serializers.CharField()
    section = serializers.CharField(required=False)

Now, when I give blank input ("") to "section" while PUT, then I receieve error (though I have given required=False) as

{
  "section": [
    "This field may not be blank."
  ]
}

I want something like this, If I give both "clas" and "section" as input then my request.data should give

{"clas": "my_input", "section": "my_input"}

and when I give only "clas" then request.data should give

{"clas": "my_input" }

NOT

{"clas": "my_input", "section": ""}

Then in my view, I want to give a default value to a variable based on field "section" is there or not as

var = request.data.get("section", "default_val")

can someone pls help here, how to achieve this behaviour.

CodePudding user response:

I can not remember actuately, but you should make sure your model are nullable first.Is is marked as "blank=True" or "Null=True"?

CodePudding user response:

In addition to adding required=False, you should also add allow_blank=True and allow_null=True to this field then it accepts an empty input for this field or None value.

By adding these your view will look like this:

class DummySerializer(serializers.Serializer):
    clas = serializers.CharField()
    section = serializers.CharField(required=False, allow_blank=True, allow_null=True)

Reference: CharField [drf-docs]

  • Related