[Django]-How to create a required Boolean field in recent Django REST Framework?

2👍

Disclaimer: This is not an answer to the OP, but I’m explaining why DRF has this behavior


In short, this happens only if you try to POST through HTML form (DRF Web API Console). If you try through POSTMAN Console, it will raise the Validation Error


Why this??

If you inspect the type of request.data in both case, it will be as

| Request Source    | Input data type   |
|------------------ |-----------------  |
| DRF HTML Input    | QueryDict         |
| POSTMAN API call  | dict              |

Where the change happens?

The get_value() method of Field class causing the behavior. In that, a check happens as,

if html.is_html_input(dictionary):
    ....... do something

from that if clause, the EMPTY/BLANK value became False



Solution

Create custom boolean field for your serializer override it’s get_value() method

from rest_framework.fields import empty


class CustomBooleanField(serializers.BooleanField):
    def get_value(self, dictionary):
        return dictionary.get(self.field_name, empty)


class FooSerializer(serializers.ModelSerializer):
    bar = CustomBooleanField(required=True)

    class Meta:
        fields = '__all__'
        model = Foo

Screenshots

1. DRF Web API console
enter image description here

2. POSTMAN API Console
enter image description here

👤JPG

1👍

Add extra_kwargs to your ModelSerializer as suggested below.

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = "__all__"
        extra_kwargs = {'bar': {'required': True}}

This set required=True argument in bar field.

If you have any further questions than please ask to the comments section.

Leave a comment