简体   繁体   English

django rest 框架序列化程序将字段值保存为空字符串,但没有错误

[英]django rest framework serializer saving field value as empty strings, but no errors

django rest framework serializer saving field value as empty strings, but no errors django rest 框架序列化程序将字段值保存为空字符串,但没有错误

views.py视图.py

from django.shortcuts import render
from rest_framework import viewsets

from rest_framework.authentication import TokenAuthentication

from .models import MyTodo
from .serializers import  MyTodoSerializer


class MyTodoView(viewsets.ModelViewSet):

    queryset = MyTodo.objects.all()
    serializer_class = MyTodoSerializer

and my model is我的 model 是

models.py模型.py

from django.db import models

# Create your models here.

class MyTodo(models.Model):
    # Autoincrement id
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=200, blank=True, default='')
    description = models.CharField(max_length=20, blank=True, default='')
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

and my serializer is我的序列化器是

serializers.py序列化程序.py

from rest_framework import serializers
from mytodo.models import MyTodo

class MyTodoSerializer( serializers.ModelSerializer ):

    title = serializers.CharField(max_length=200, default='')
    description = serializers.CharField(max_length=200, default='')
    created_on = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False)

    def create(self, validated_data):
        return MyTodo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.description = validated_data.get('description', instance.description)
        instance.created_on = validated_data.get('created_on', instance.created_on )
        instance.save()
        return instance


    class Meta:
        model = MyTodo
        fields = [ 'id','url','title','description', 'created_on' ]

Looks pretty simple, straight forward but by CURL calls are saving empty fields, but Browsable API View is working very fine.看起来很简单,直接但通过 CURL 调用保存空字段,但 Browsable API View 工作得很好。 Please tell me what am I doing wrong.请告诉我我做错了什么。

Here is what I am trying to do这是我想做的

Curl Client Curl 客户

#!/bin/bash

b64credential=$(echo 'admin:admin' | base64)

access_token=$(curl -d "username=admin&password=admin"  -X POST 'http://localhost:8000/api/token/' \
-H 'Accept:application/json' \
-H "Authorization:Basic  ${b64credential}" | jq --raw-output '.access' )

echo "Access token : $access_token"

# post a todo to  mytodo api

curl -vvv -L -d '{"title": "Awesome things to be done" ,"description": "Really great things stay alert"}' \
     -X POST 'http://localhost:8000/mytodo/' \
     -H 'Accept:application/json' \
     -H "Authorization:Bearer  ${access_token}"

the response looks like this响应看起来像这样

{"id":23,"url":"http://localhost:8000/mytodo/23/","title":"","description":"","created_on":"2021-05-14T10:02:45"}

Here are couple more questions这里还有几个问题

  1. Why I get title:"", description: "",为什么我得到标题:“”,描述:“”,

  2. in the view, I have only serializer_class = MyTodoSerializer have no information about actual request processing, how Django is correctly calling the right method MyTodoSerializer.create()在视图中,我只有serializer_class = MyTodoSerializer没有关于实际请求处理的信息,Django 如何正确调用正确的方法 MyTodoSerializer.create()

You have set '' as default value and cURL payload is not passed to Django.您已将''设置为默认值,并且 cURL 有效负载未传递给 Django。

The reason is your header is wrong.原因是你的header打错了。

Is

     -H 'Accept:application/json' \

should be应该

     -H "Content-Type: application/json"

Try this instead.试试这个。

curl -vvv -L -d '{"title": "Awesome things to be done" ,"description": "Really great things stay alert"}' -X POST 'http://localhost:8000/mytodo/' -H "Content-Type: application/json" -H "Authorization:Bearer  ${access_token}"

The difference between these two headers can be found here .可以在此处找到这两个标头之间的区别。

django rest framework serializer saving field value as empty strings, but no errors django rest 框架序列化程序将字段值保存为空字符串,但没有错误

views.py视图.py

from django.shortcuts import render
from rest_framework import viewsets

from rest_framework.authentication import TokenAuthentication

from .models import MyTodo
from .serializers import  MyTodoSerializer


class MyTodoView(viewsets.ModelViewSet):

    queryset = MyTodo.objects.all()
    serializer_class = MyTodoSerializer

and my model is我的 model 是

models.py模型.py

from django.db import models

# Create your models here.

class MyTodo(models.Model):
    # Autoincrement id
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=200, blank=True, default='')
    description = models.CharField(max_length=20, blank=True, default='')
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

and my serializer is我的序列化程序是

serializers.py序列化程序.py

from rest_framework import serializers
from mytodo.models import MyTodo

class MyTodoSerializer( serializers.ModelSerializer ):

    title = serializers.CharField(max_length=200, default='')
    description = serializers.CharField(max_length=200, default='')
    created_on = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False)

    def create(self, validated_data):
        return MyTodo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.description = validated_data.get('description', instance.description)
        instance.created_on = validated_data.get('created_on', instance.created_on )
        instance.save()
        return instance


    class Meta:
        model = MyTodo
        fields = [ 'id','url','title','description', 'created_on' ]

Looks pretty simple, straight forward but by CURL calls are saving empty fields, but Browsable API View is working very fine.看起来很简单,直截了当,但通过 CURL 调用正在保存空字段,但可浏览的 API 视图工作得很好。 Please tell me what am I doing wrong.请告诉我我做错了什么。

Here is what I am trying to do这是我想要做的

Curl Client Curl客户端

#!/bin/bash

b64credential=$(echo 'admin:admin' | base64)

access_token=$(curl -d "username=admin&password=admin"  -X POST 'http://localhost:8000/api/token/' \
-H 'Accept:application/json' \
-H "Authorization:Basic  ${b64credential}" | jq --raw-output '.access' )

echo "Access token : $access_token"

# post a todo to  mytodo api

curl -vvv -L -d '{"title": "Awesome things to be done" ,"description": "Really great things stay alert"}' \
     -X POST 'http://localhost:8000/mytodo/' \
     -H 'Accept:application/json' \
     -H "Authorization:Bearer  ${access_token}"

the response looks like this响应看起来像这样

{"id":23,"url":"http://localhost:8000/mytodo/23/","title":"","description":"","created_on":"2021-05-14T10:02:45"}

Here are couple more questions这里还有几个问题

  1. Why I get title:"", description: "",为什么我得到标题:“”,描述:“”,

  2. in the view, I have only serializer_class = MyTodoSerializer have no information about actual request processing, how Django is correctly calling the right method MyTodoSerializer.create()在视图中,我只有serializer_class = MyTodoSerializer没有关于实际请求处理的信息,Django 如何正确调用正确的方法 MyTodoSerializer.create()

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

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