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
👤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.
- [Django]-Proper way to add code to logout view in Django
- [Django]-Python/Django: How to render user-submitted videos code fragments as embedded videos?
- [Django]-Django and radio buttons
Source:stackexchange.com