Django:Webp转换失败并创建空图片元素,同时所有调试工作都失败

6fe3ivhb  于 2023-01-06  发布在  Go
关注(0)|答案(1)|浏览(102)
    • bounty将在7天后过期**。回答此问题的人有资格获得+50的声望奖励。Matthias希望吸引更多人关注此问题。

更新:

在对已接受的答案做了一些小的修改后,我能够解决它:

class GalleryView(APIView):
  parser_class = (FileUploadParser,)

  def post(self, request):
    # Extract the facility ID and list of pictures from the request
    print('post method called')
    facility_id = request.data.get('facility')
    pictures = request.data.getlist('pictures')

    print(facility_id, pictures)

    facility = get_object_or_404(Facility, id=facility_id)

    try:
      gallery = Gallery.objects.get(facility=facility)
    except Gallery.DoesNotExist:
      gallery = Gallery.objects.create(facility=facility)

    with transaction.atomic():
        for picture in pictures:
            print('for loop executing')
            try:
                webp_image = BytesIO()
                image = Image.open(picture)
                image.save(webp_image, format='webp', quality=5)
                print(webp_image)
                
                file_name = picture.name
                if picture.name.lower().endswith(('.jpg', '.jpeg', '.png')):
                    file_name = f"{os.path.splitext(picture.name)[0]}.webp"
                else:
                    file_name = picture.name
                file_object = ContentFile(webp_image.getvalue(), name=file_name)
                print(file_object)
                picture_obj = Picture.objects.create(picture=file_object)
                print(picture_obj)
                gallery.pictures.add(picture_obj)
                print(gallery)
            except Exception as e:
                print(type(e))
                continue

    serializer = GallerySerializer(gallery)
    return Response(serializer.data, status=201)

我试着创建一个上传表单来上传多张需要转换成webp的图片。在我添加webp转换位之前,一切都很好。我试着添加异常和print语句来跟踪这个问题,但是没有出现异常。相反,它显示了所有成功的迹象,并在数据库中创建了一个空的"picture"元素。我正在使用django cookiectter项目。有人知道是什么引起的吗?
models.py

def upload_gallery_image(instance, filename):
  # Print a message to indicate that the function was called
  print(instance, filename)
  return f'galleries/{instance.facility.id}/{filename}'

class Picture(models.Model):
  picture = models.ImageField(upload_to=upload_gallery_image)
  
class Gallery(models.Model):
  facility = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='tourphotos')
  pictures = models.ManyToManyField(Picture, related_name='galleries')

views.py

class GalleryView(APIView):
  parser_class = (FileUploadParser,)

  def post(self, request):
    # Extract the facility ID and list of pictures from the request
    print('post method called')
    facility_id = request.data.get('facility')
    pictures = request.data.getlist('pictures')

    print(facility_id, pictures)

    facility = get_object_or_404(Facility, id=facility_id)

    try:
      gallery = Gallery.objects.get(facility=facility)
    except Gallery.DoesNotExist:
      gallery = Gallery.objects.create(facility=facility)

    for picture in pictures:
        print('for loop executing')
        try:
            webp_image = BytesIO()
            image = Image.open(picture)
            image.save(webp_image, format='webp', quality=75)
            print(webp_image)
            file_object = ContentFile(webp_image.getvalue())
            print(file_object)
            picture_obj = Picture.objects.create(picture=file_object)
            print(picture_obj)
            gallery.pictures.add(picture_obj)
            print(gallery)
        except Exception as e:
            print(type(e))
            continue

    webp_image.close()

    serializer = GallerySerializer(gallery)
    return Response(serializer.data, status=201)

serializers.py

class PictureSerializer(serializers.ModelSerializer):
    class Meta:
        model = Picture
        fields = ('id', 'picture')

class GallerySerializer(serializers.ModelSerializer):
    pictures = PictureSerializer(many=True)
    class Meta:
        model = Gallery
        fields = ('id', 'pictures')

服务器响应:

django          | post method called
django          | 24 [<InMemoryUploadedFile: 156f9f885e468c60dd7d6d539f2ee1bb.webp (image/webp)>]
django          | for loop executing
django          | <_io.BytesIO object at 0x7fbfdb14eef0>
django          | Raw content
django          | Picture object (304)
django          | Gallery object (59)
django          | 172.21.0.1 - - [02/Jan/2023 11:09:44] "POST /api/multipleupload/ HTTP/1.1" 201 -
2guxujil

2guxujil1#

尝试将名称添加到ContentFile,在您的情况下更改为:

file_object = ContentFile(webp_image.getvalue(), name=picture)

ContentFile不会创建没有文件名的文件。

相关问题