无法在POST方法Django rest fram中传递来自kwargs的值

2024-04-25 13:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

当我尝试使用perform\u create方法传递course\u id的值时,它显示了这个错误。。。你知道吗

ValueError at /course/9f77f4a9-0486-44f3-8bea-4908adb7d3ca/add/
Cannot assign "'9f77f4a9-0486-44f3-8bea-4908adb7d3ca'": "Content.course_id" must be a "Course" instance.
    Request Method: POST
    Request URL:    http://127.0.0.1:8000/course/9f77f4a9-0486-44f3-8bea-4908adb7d3ca/add/
    Django Version: 2.2.5
    Exception Type: ValueError
    Exception Value:    
    Cannot assign "'9f77f4a9-0486-44f3-8bea-4908adb7d3ca'": "Content.course_id" must be a "Course" instance.

这是我的视图.py你知道吗

class ContentAdd(generics.ListAPIView, mixins.CreateModelMixin):
    queryset = Content.objects.all()
    serializer_class = ContentSerializer

    def post(self, request, *args, **kwargs):
        saveData = self.create(request, *args, **kwargs)
        response_data = {}
        response_data["data"] = saveData.data
        response_data["errors"] = {}
        return Response(response_data, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        id = self.kwargs.get("course_id")
        serializer.save(course_id=id)

这是我的序列化程序.py你知道吗

class ContentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Content
        fields = [
            'title',
            'description',
            'serial',
            'file',
            'file_type',
        ]

这是我的型号.py你知道吗

class Content(models.Model):
    content_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    course_id = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="content_course_id", to_field='course_id')
    file = models.FileField(upload_to=gen_pic_path,blank=False, null=False)
    file_type = models.BooleanField(blank=False, null=False)    # content/attachment
    serial = models.IntegerField()
    title = models.CharField(max_length=200)
    description = models.TextField()

这是url路径

path('course/<course_id>/add/', ContentAdd.as_view()),

Tags: pyselfaddidfalsedatamodelsresponse