简体   繁体   中英

Django rest api expected string or buffer on PATCH

I'm making a Django application, where I am sending requests through rest API. I am using POST and GET and all works pretty well, but when I am trying to use PATCH (as I must firstly upload field "start_time", and then add field "time"), I'm getting following error:

match = time_re.match(value) TypeError: expected string or buffer

Surely it is about views.py, but I cannot find clear recipe how to do that, thus I don't know where I am wrong.

Thank you.

Views.py

...
elif request.method = 'PATCH':
    serializer = TABLESerializer(data=request.data, partial=True)
    if serializer.is_valid():
        obj = TABLE.objects.get(start_time=request.data['start_time'])
        obj.time = serializer['time']
        obj.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Serializers.py

class TABLESerilizer(serializers.serializer):
    start_time = serializers.DateTimeField(format = None, allow_null=True)
    time = serializers.TimeField(format=None, required=False)

models.py

class TABLE(models.Model):
    start_time=models.DateTimeField(primary_key=True)
    time = models.TimeField(null= True, blank= True, default = '00:00:00')

format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set.

But in your case you set it to None . we get error when python try to parse the data into time object with format None format must me like HH:MM:SS , etc.

update your serializer like below

from rest_framework.settings import api_settings

class TABLESerilizer(serializers.serializer):
    start_time = serializers.DateTimeField(format=api_settings.TIME_FORMAT)
    time = serializers.TimeField(format=api_settings.TIME_FORMAT)

References: http://www.django-rest-framework.org/api-guide/fields/#timefield
https://github.com/django/django/blob/master/django/utils/dateparse.py#L80

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM