model.py
class Form(models.Model):
no = models.IntegerField()
finish_date = models.DateField(blank=True, null=True)
serializers.py
class FormSerializer(serializers.ModelSerializer):
class Meta:
model = Form
fields = '__all__'
if I try:
http http://127.0.0.1:8000/api/forms no=112 "finish_date"=""
It returns the error:
"finish_date": [
"Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
]
If I set "finish_date" to null , this post works.
And StringField(blank=True, null=True)
will not get the error.
How to solve?
The problem is that the DateTimeField
doesn't currently support the allow_blank
keyword argument.
It does however support allow_null
, so you have two options:
Scrub "finish_date": ""
-> "finish_date": null
*before sending to your server
If you are using JavaScript to submit your form, you'll probably have do something like this:
if (data["finish_date"] == "") {
data["finish_date"] = null;
}
Scrub "finish_date": ""
-> "finish_date": None
in your serializer.
You can easily do this using the .to_internal_value()
method on the ModelSerializer
class FormSerializer(serializers.ModelSerializer):
class Meta:
model = Form
fields = '__all__'
def to_internal_value(self, data):
# check for "finish_date": "" and convert to None
# This must be done before .validate()
if data['finish_date'] == '':
data['finish_date'] = None
return super(FormSerializer, self).to_internal_value(data)
the .to_internal_value()
method is mentioned a lot in the Django Rest Framework Fields API Reference
Now in the above model, you have a DateField, and the DateField accepts certain formats similar to the ones shown in the error in your post.When you post with:
http http://127.0.0.1:8000/api/forms no=112 "finish_date"=""
You are actually passing an empty string("") to the serializer, which is not a valid format for the DateField. Instead try the Post without passing the "finish_date" arg, I think it will work then. Or maybe you could pass with some default date in the past instead of passing an empty string .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With