swagger 发送外键作为参数导致此字段为必填错误

sqxo8psd  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(96)

我试图创建一个应用程序,用户可以登录和创建任务。我的django应用程序的代码托管在here
我使用JWT身份验证和drf-yasg来生成swagger。因此TaskSerializer接受3个参数

  • taskname是字符串
  • 布尔型完成
  • username,应指向用户模型

我的TaskModel如下

class Tasks(models.Model):
    taskname=models.CharField(max_length=10)
    completion=models.BooleanField(default=False)
    username = models.ForeignKey(User, on_delete=models.CASCADE)

字符串
我的TaskSerializer

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tasks
        fields = ['taskname', 'completion', 'username']


我的TaskView如下:

class TaskView(APIView):
    def get(self, request):
        token = request.COOKIES.get('jwt')
        if not token:
            raise AuthenticationFailed('Unauthenticated!')

        try:
            payload = jwt.decode(token, 'secret', algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('Unauthenticated!')

        tasks = Tasks.objects.filter(username=payload['username']).all()
        return Response(tasks)

    @swagger_auto_schema(
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'taskname': openapi.Schema(type=openapi.TYPE_STRING, description='Add taskname'),
                'completion': openapi.Schema(type=openapi.TYPE_BOOLEAN, description='completion'),
            }
        )
    )
    def post(self, request):
        token = request.COOKIES.get('jwt')
        if not token:
            raise AuthenticationFailed('Unauthenticated!')

        try:
            payload = jwt.decode(token, 'secret', algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('Unauthenticated!')
        req_data = {
            "username": User.objects.filter(username=payload['username']).first(),
            "taskname": request.data['taskname'],
            "completion": request.data['completion'],
        }
        print(5*'*', req_data)
        serializer = TaskSerializer(
            data=request.data
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


然而,当我创建一个任务,我可以从令牌中检索用户,并通过swagger将post请求发送到/task时,我得到以下错误:

{
  "username": [
    "This field is required."
  ]
}

jgovgodb

jgovgodb1#

你正在发送错误的数据到序列化器。它应该像这样:

serializer = TaskSerializer(data=req_data)

字符串

相关问题