Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post empty date field error with Django rest framework

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?

like image 966
wgf4242 Avatar asked Oct 22 '17 06:10

wgf4242


2 Answers

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:

  1. Clean Data Before Sending

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;
}
  1. Clean Data After Receiving

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

like image 148
Adonis Gaitatzis Avatar answered Nov 04 '22 02:11

Adonis Gaitatzis


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 .

like image 5
rajkris Avatar answered Nov 04 '22 02:11

rajkris