0

I have a simple view with which I want to be able to set a nullable TimeField to None:

class Device(models.Model):
    alarm_push = models.TimeField(null=True, blank=True)

class DeviceSettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Device
        fields = ('alarm_push',)


class DeviceSettingsView(RetrieveUpdateAPIView):
    serializer_class = DeviceSettingsSerializer
    lookup_field = 'uuid'

    def get_queryset(self):
        return Device.objects.all()

But if I try to PATCH data like {'alarm_push': None} I get an error like {"alarm_push":["Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]."]}

How can I set alarm_push to None?

David Schumann
  • 13,380
  • 9
  • 75
  • 96
  • I think there is a [difference between](https://stackoverflow.com/questions/8609192/differentiate-null-true-blank-true-in-django) None and null that we can't overlook. When you PATCH data with None being assigned to 'alarm_push', I believe you are not letting Django 'do its thing' by automatically setting the value to null. Instead it's reading the None as a value, trying to put it into a time format, and failing because it's None. Can you PATCH with 'alarm_push' being set to nothing? I don't know enough about this to form an answer! Just a thought! – cosinepenguin Sep 27 '17 at 15:24

1 Answers1

2

As your Serializer is a ModelSerializer DRF will use a TimeField() for your alarm_push model attribute. When you checkout the sourcecode of the DRF Timefield https://github.com/encode/django-rest-framework/blob/master/rest_framework/fields.py#L1278 you can see that to_internal_value is raising your error when every attempt of parsing the value failes.

So to have your TimeField be empty you should patch {"alarm_push": ""} with an empty string to represent an empty state.