简体   繁体   English

Django Rest API预期的字符串或PATCH上的缓冲区

[英]Django rest api expected string or buffer on PATCH

I'm making a Django application, where I am sending requests through rest API. 我正在制作Django应用程序,在这里我通过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: 我正在使用POST和GET,并且一切正常,但是当我尝试使用PATCH时(因为我必须首先上载字段“ start_time”,然后添加字段“ time”),出现以下错误:

match = time_re.match(value) TypeError: expected string or buffer match = time_re.match(value)TypeError:预期的字符串或缓冲区

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. 当然,这是关于views.py的问题,但是我找不到明确的方法来做到这一点,因此我不知道我哪里做错了。

Thank you. 谢谢。

Views.py 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 Serializers.py

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

models.py 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. format-代表输出格式的字符串。 If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. 如果未指定,则默认为与TIME_FORMAT设置键相同的值,除非设置,否则为'iso-8601'。

But in your case you set it to None . 但是根据您的情况,将其设置为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. 当python尝试将数据解析为格式为None时间对象时,我们会收到错误消息,格式必须为HH:MM:SS ,等等。

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 参考: http : //www.django-rest-framework.org/api-guide/fields/#timefield
https://github.com/django/django/blob/master/django/utils/dateparse.py#L80 https://github.com/django/django/blob/master/django/utils/dateparse.py#L80

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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