0

我有一个项目,用户可以在创建公告时上传多张照片,当使用表单数据从邮递员发送请求时,公告已成功添加但图像未上传,当使用内容类型设置为的原始 Json 时:multipart/form-数据,我收到以下错误:

"detail": "Multipart form parse error - Invalid boundary in multipart: None"

从可浏览 API 发送以下请求时:

{
    "name": "tractor",
    "address": "any",
    "price": 100,
    "author": 17,
    "photo": [
        {
            "name": "tractor",
            "image": "/C:/Users/Admin/Downloads/marteau.jpg"
        }
    ]
}

我收到以下错误:

"detail": "Multipart form parse error - Invalid boundary in multipart: None"

他是我的代码:

模型.py

class Photo(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to=nameFile, blank=True, null=True)

  
class Announcement(models.Model):
    author = models.ForeignKey(
        User, on_delete=models.CASCADE,  related_name='announcements')
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    price = models.FloatField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    rating = models.FloatField(blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True)
    photo = models.ManyToManyField(Photo, blank=True)

视图.py

class AnnouncementCreate(CreateAPIView):
    queryset = models.Announcement.objects.all()
    serializer_class = AnnouncementSerializer
    parser_classes = (FormParser,MultiPartParser)
    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

class PhotoViewSet(ListAPIView):

    queryset = models.Photo.objects.all()
    serializer_class = PhotoSerializer

    def post(self, request, *args, **kwargs):
        file = request.data.get('image')
        image = models.Photo.objects.create(image=file)
        return HttpResponse(json.dumps({'message': "Uploaded"}), status=200)

序列化程序.py

class AnnouncementSerializer(WritableNestedModelSerializer, serializers.ModelSerializer):
    parameters = ParameterSerializer(many=True, required=False)
    photo = PhotoSerializer(many=True, required=False)
class Meta:
        model = Announcement
        fields = ['id', 'name', 'address', 'date',
                  'price', 'description', 'author', 'parameters', 'photo']

class PhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo
        fields = ('name', 'image')


4

2 回答 2

0

在询问这个问题之前,我已经打开了一个问题,遗憾的是,DRF 不支持带有多部分/表单数据的嵌套可写序列化程序。

这是我的问题:https ://github.com/encode/django-rest-framework/issues/7262

如果您可以摆脱嵌套的序列化程序,那么您将能够正常上传带有 multipart/form-data 的文件,否则,您必须使用 application/json 并将您的文件编码为 base64 字符串,这样您才能上传带有嵌套序列化程序的文件。

于 2021-10-07T19:36:58.563 回答
0

你必须使用 MultiPartParser 因为 DRF 中的默认解析器是 Json 解析器 你没有发送 JSON 但你正在发送二进制

https://www.django-rest-framework.org/api-guide/parsers/

于 2021-10-08T04:00:57.170 回答