ErrorDetail(string='This field is required.',code='required')] Django Rest Framework Code require error

tquggr8v  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(199)

当我保存到下面的数据时,提到获取错误。'grp_name':[ErrorDetail(string='This field is required.',code='required')]}
Modely.py文件

# Create your models here.
class GroupMaster(models.Model):
    status_type = (
        ("a","Active"),
        ("d","Deactive"),
    )
    code = models.CharField(max_length=255, unique=True, default=None, null=True, blank= True)
    grp_name = models.CharField(max_length=50, unique=True)
    status = models.CharField(max_length=1, choices=status_type , default='a')
    create_by = models.ForeignKey(User, on_delete=models.CASCADE)
    create_at = models.DateField(auto_now_add=True)
    update_at = models.DateField(auto_now = True)

    def __str__(self):
        return str(self.grp_name)

序列化器.py文件

from rest_framework import serializers
from base.models import GroupMaster

class GroupMasterSerializer(serializers.ModelSerializer):
    class Meta:
        model = GroupMaster
        fields = "__all__"
        extra_kwargs = {
                        'code': {'required': False}, 
                        'create_by': {'required': False},
                        'create_at': {'required': False},
                        'update_at': {'required': False},
                        }

查看.py文件

from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
from base.models import GroupMaster
from .serializers import GroupMasterSerializer

@api_view(['POST'])
def Add_Grp(request):
    serializer = GroupMasterSerializer(data = request.data)
    if serializer.is_valid():
        serializer.save()
    else:
        print(str(serializer.errors))
    return Response("asdf")

表单.html文件

var grp_add_form = document.getElementById('grp_add_form')
  grp_add_form.addEventListener('submit', function (e) {
    e.preventDefault();
    var url = 'http://127.0.0.1:8000/api/grp/add/'
    var id_grp_name = document.getElementById('id_grp_name').value
    console.log(id_grp_name)
    var id_status = document.getElementById('id_status').value
    var id_code = "d"
    fetch(url,{
          method:'POST',
          headers:{
            'Content-type':'application/json',
            'X-CSRFToken':csrftoken,
            },
            body:JSON.stringify({
              'id_code':id_code,
              'id_grp_name':id_grp_name,
              'id_status':id_status,
            })
          }
      ).then(function(response) {
        console.log('test')
      })
  });   
</script>

我已经代码字段定义null=true和blank=true现在我不知道为什么这个错误获取和提交不工作的请求。用户保存

inn6fuwd

inn6fuwd1#

看起来你的GroupMaster模型需要一个grp_name字段,但你没有在请求中发送它。你也能分享一下GroupMaster模型吗?
---更新答案
您的错误消息

{'grp_name': [ErrorDetail(
        string='This field is required.', 
        code='required'
        )]
 }

这意味着你忘记了将grp_name字段传递给请求,因此,当验证serializer.is_valid()上的序列化器所需字段时,模型序列化器GroupMasterSerializer会弹出此错误消息。
如果没有自定义,Django Rest Framework ModelSerializers字段仅基于Django Models字段定义进行序列化/反序列化。
默认情况下,Django模型字段定义带有blank=Falsenull=False,这意味着该字段是模型所必需的。
在你的模型GroupMaster中,grp_name被定义为grp_name = models.CharField(max_length=50, unique=True),所以,它是blank=Falsenull=False,在某种程度上,你总是需要向它传递一个值。
我在终端上做了这个测试,效果很好:

s = GroupMasterSerializer(
    data={
        'id_code': 'id_code',
        'id_status': 'id_status',
        'id_grp_name': 'id_grp_name',
        'grp_name': 'grp_name'
    }
)
s.is_valid()

真的

s.errors

{}

相关问题