As of ver. 3x
DJango Rest Framework does not provide DateField which allows blank values, you either do not have to send the field in the payload or explicitly set null
as the field value, but you cannot set ""
blank values.
To solve this issue, I have implemented my own custom field which is built on top of DRF DateField, so you do not have to worry about compromising on your existing requirements! ;)
# sample.py
from rest_framework import serializers
class DateField(serializers.DateField):
"""
Date field which allows blank values.
As of djangorestframework 3x, DRF does not provide a date field which
allows blank ("") values, so this field is built on top of DRF DateField
which provides functionality to accept blank values.
"""
allow_blank = None
def __init__(self, *args, **kwargs):
self.allow_blank = kwargs.pop("allow_blank", False)
super().__init__(format, *args, **kwargs)
def to_internal_value(self, data):
# calc length if blank values are allowed,
# this improves performance a bit
if self.allow_blank:
if len(data) == 0:
return data
return super().to_internal_value(data)
def to_representation(self, value):
# DRF by default returns None if no value is set
# so no custom implementation is required
return super().to_representation(value)
Usage:
from sample import DateField
my_date_field = DateField(
allow_blank=True,
)