Django-REST API在电子邮件存在时引发串行器错误

时间:2017-10-24 11:45:29

标签: python django post get

快速浏览,前端向我发送电子邮件,密码和确认密码。

我将它们存储在API中,然后将存储在数据库中,但同时,我只在发送的电子邮件不存在时保存它们

首先是我的 views.py

class UserList(APIView):

def get(self,request):
    users = Users.objects.all()
    serializer = UserSerializer(users,many=True)
    return Response(serializer.data)

def post(self,request):

    serializer = UserSerializer(data=request.data)
    #here i serialize the data entered by the user
    if serializer.is_valid():
        try:
          #and then i check if the email already exists or not, if it not exist, it will save it in the API, if not it should raise an errro!, i tried saying serializers.validationerror bs that wouldn't work at all.

            match = Users.objects.get(email=serializer.validated_data["email"])
        except Users.DoesNotExist:
            # Unable to find a user, this is fine]
            serializer.save()
            print ('money here come the money')
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        raise (?!)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

您需要返回Response个对象,而不是引发异常。

<强>解决方案

return Response({
  'success': False,
  'detail': 'Email already exists'
}, status=status.HTTP_400_BAD_REQUEST)

raise(?!)替换为上述代码。