Django自定义保存模型创建重复文件

qv7cva1a  于 2023-02-14  发布在  Go
关注(0)|答案(2)|浏览(142)

我试着把上传的图片也保存为缩略图,这很有效。问题是当我更新的时候,自定义方法把缩略图保存在了另一个目录中。所以我修改了我的保存函数,看起来像这样。
models.py

class Photo(models.Model):
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=255)
    created = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to='photos/%Y%m')
    thumbnail = models.ImageField(blank=True, upload_to='thumbnails/%Y%m')
    submitter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    year = models.ForeignKey(Year, blank=True, on_delete=models.CASCADE)
    people = TaggableManager(through=TaggedPeople, verbose_name='People')
    tags = TaggableManager(through=TaggedGeneric, verbose_name='Tags')

    def save(self, *args, **kwargs):
         try:
             this = Photo.objects.get(id=self.id)
             if this.thumbnail != self.thumbnail:
                 this.thumbnail.delete(save=False)
         except:
            if self.thumbnail:
                img = Image.open(BytesIO(self.thumbnail.read()))

                if hasattr(img, '_getexif'):
                    exif = img._getexif()
                    if exif:
                        for tag, label in ExifTags.TAGS.items():
                            if label == 'Orientation':
                                orientation = tag
                                break
                        if orientation in exif:
                            if exif[orientation] == 3:
                                img = img.rotate(180, expand=True)
                            elif exif[orientation] == 6:
                                img = img.rotate(270, expand=True)
                            elif exif[orientation] == 8:
                                img = img.rotate(90, expand=True)

                img.thumbnail((360,360), Image.ANTIALIAS)
                output = BytesIO()
                img.save(output, format='JPEG', quality=95)
                output.seek(0)
                self.thumbnail = File(output, self.thumbnail.name)

            return super().save(*args, **kwargs)

    def __str__(self):
        return self.title

我的观点

class PhotoCreateView(LoginRequiredMixin, CreateView):
    model = Photo
    fields = ['image', 'title', 'description', 'year', 'people', 'tags']
    template_name = 'photoapp/create.html'
    success_url = '/photo/?page=1'
    extra_context = {'tags':GenericTag.objects.all().order_by('name'),'people':PeopleTag.objects.all().order_by('name'),}

    def form_valid(self, form):
        form.instance.thumbnail = self.request.FILES['image']
        form.instance.submitter = self.request.user
        return super().form_valid(form)

class PhotoUpdateView(LoginRequiredMixin, UpdateView):
    template_name = 'photoapp/update.html'
    model = Photo
    fields = ['title', 'description', 'year', 'people', 'tags']
    success_url = '/photo/?page=1'

所以CreateView现在工作正常,我已经停止了重复的缩略图文件,但UpdateView不工作。我该如何解决这个问题?

4uqofj5v

4uqofj5v1#

我想通了,我只需要在尝试部分加一个保存。

def save(self, *args, **kwargs):
         try:
             this = Photo.objects.get(id=self.id)
             if this.thumbnail != self.thumbnail:
                 this.thumbnail.delete(save=False)
             return super().save(*args, **kwargs)
         except:
            if self.thumbnail:
                img = Image.open(BytesIO(self.thumbnail.read()))

                if hasattr(img, '_getexif'):
                    exif = img._getexif()
                    if exif:
                        for tag, label in ExifTags.TAGS.items():
                            if label == 'Orientation':
                                orientation = tag
                                break
                        if orientation in exif:
                            if exif[orientation] == 3:
                                img = img.rotate(180, expand=True)
                            elif exif[orientation] == 6:
                                img = img.rotate(270, expand=True)
                            elif exif[orientation] == 8:
                                img = img.rotate(90, expand=True)

                img.thumbnail((360,360), Image.ANTIALIAS)
                output = BytesIO()
                img.save(output, format='JPEG', quality=95)
                output.seek(0)
                self.thumbnail = File(output, self.thumbnail.name)

            return super().save(*args, **kwargs)
vecaoik1

vecaoik12#

我在Django-Wagtail中也有类似的抱怨,保存www.example.com()时会在文件系统上复制导入的映像。一定要解决这个问题。我使用Python Glob来获取路径,并在加载保存函数后使用操作系统来删除原始映像。image.save但事实就是如此。 I wanted to capture the issue for others - as there isn't much on the web about this. It's frustrating, doubles your disk space usage due to this functionality if you aren't careful! I don't like that it renames the files/moves them, but it is what it is.

from django.core.management.base import BaseCommand, CommandError
from wagtail.images.models import Image
from django.core.files.images import ImageFile
import os
from os import path
import glob
#import sqlite3

class Command(BaseCommand):

help = "just a thing to "

def handle(self, *args, **options):

    target_path = "/home/inmyth/inmyth/media/images/"

    my_images = []

    if os.path.exists(target_path):
  
        my_images = glob.glob(target_path + "*.png")

        for mj_imgs in my_images:
            print(mj_imgs)
            image_file = ImageFile(open(mj_imgs, 'rb'), name=mj_imgs[:-4])
            img_label = mj_imgs.rfind("/") + 1
            image = Image(title=mj_imgs[img_label:-4], file=image_file)
            image.save()
            os.remove(mj_imgs)
    pass

相关问题