我有一个项目,用户可以在创建公告时上传多张照片,当使用表单数据从邮递员发送请求时,公告已成功添加但图像未上传,当使用内容类型设置为的原始 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')