Django Rest框架assertionError

时间:2020-01-18 10:33:52

标签: python django-rest-framework

AssertionError:传递了序列化器data关键字参数后,必须先调用.is_valid(),然后再尝试访问序列化的.data表示形式。 您应该先致电.is_valid(),或者访问.initial_data

views.py:

from rest_framework.views import APIView
from rest_framework.response import Response
from drfw.serializers import NameSerializers
class restapiView(APIView):
    def get(self,request,*args,**kwargs):
        alphabets=['A','B','C','D','E']
        return Response({'msg':'latters','alphabets':alphabets})
    def post(self,request,*args,**kwargs):
        serializer=NameSerializers(data=request.data)
        if serializer.is_valid:
            name=serializer.data.get('name')
            msg='Hello{}'.format(name)
            return Response({'msg':msg})
        else:
            return Response(serializer.errors,status=400)

serializers.py:

from rest_framework import serializers
class NameSerializers(serializers.Serializer):
    name=serializers.CharField(max_length=30)

1 个答案:

答案 0 :(得分:1)

is_valid是一种方法。所以您需要调用它。

if serializer.is_valid:替换为if serializer.is_valid():