Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

I using DatePicker from '@mui/x-date-pickers'.
Because html input can't handle null,
so DatePicker sends empty string if date value is null.
However DRF raise Error as empty string is not suit for format for DateField and DateTimeField.

I think it is useful that DateField and DateTimeField can take empty string as null.
Some people think too.
ref. https://stackoverflow.com/questions/46871046/post-empty-date-field-error-with-django-rest-framework

I created my ModelSerializer so that you don't have to specify the field name every time.

from rest_framework import serializers

class ModelSerializer(serializers.ModelSerializer):

    def to_internal_value(self, data):
        for field_name, value in data.items():
            if not field_name in self.fields:
                continue
            field_object = self.fields[field_name]
            if all([
                value == "",
                field_object.allow_null,
                any([
                    isinstance(field_object, serializers.DateField),
                    isinstance(field_object, serializers.DateTimeField),
                ]),
            ]):
                data[field_name] = None
        return super().to_internal_value(data)
You must be logged in to vote

Replies: 1 comment

Comment options

At first glance, that sounds like a reasonable change to me, but I worry/wonder about why it was done this way in the first place. Can't the front-end library do some mapping there where empty is always sent as null? Or is it because the request content type is form-data and not JSON?

I created my ModelSerializer so that you don't have to specify the field name every time.

You may get a smaller/more targeted patch by creating a custom DateField + DateTimeField and optionally updating the ModelSerializer.serializer_field_mapping.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.