Django Photologue zip上传保留图片名称

时间:2016-08-26 11:53:46

标签: python django photologue

我正在研究photologue,直到现在它还是完美的。我只是想知道在上传zip图像时如何保留图像名称。

这是zip文件上传后保存功能的代码。 :

   def save(self, request=None, zip_file=None):
    if not zip_file:
        zip_file = self.cleaned_data['zip_file']
    zip = zipfile.ZipFile(zip_file)
    count = 1
    current_site = Site.objects.get(id=settings.SITE_ID)
    if self.cleaned_data['gallery']:
        logger.debug('Using pre-existing gallery.')
        gallery = self.cleaned_data['gallery']
    else:
        logger.debug(
            force_text('Creating new gallery "{0}".').format(self.cleaned_data['title']))
        gallery = Gallery.objects.create(title=self.cleaned_data['title'],
                                         slug=slugify(self.cleaned_data['title']),
                                         description=self.cleaned_data['description'],
                                         is_public=self.cleaned_data['is_public'])
        gallery.sites.add(current_site)
    for filename in sorted(zip.namelist()):

        logger.debug('Reading file "{0}".'.format(filename))

        if filename.startswith('__') or filename.startswith('.'):
            logger.debug('Ignoring file "{0}".'.format(filename))
            continue

        if os.path.dirname(filename):
            logger.warning('Ignoring file "{0}" as it is in a subfolder; all images should be in the top '
                           'folder of the zip.'.format(filename))
            if request:
                messages.warning(request,
                                 _('Ignoring file "{filename}" as it is in a subfolder; all images should '
                                   'be in the top folder of the zip.').format(filename=filename),
                                 fail_silently=True)
            continue

        data = zip.read(filename)

        if not len(data):
            logger.debug('File "{0}" is empty.'.format(filename))
            continue

        photo_title_root = self.cleaned_data['title'] if self.cleaned_data['title'] else gallery.title

        # A photo might already exist with the same slug. So it's somewhat inefficient,
        # but we loop until we find a slug that's available.
        while True:
            photo_title = ' '.join([photo_title_root, str(count)])
            slug = slugify(photo_title)
            if Photo.objects.filter(slug=slug).exists():
                count += 1
                continue
            break

        photo = Photo(title=photo_title,
                      slug=slug,
                      caption=self.cleaned_data['caption'],
                      is_public=self.cleaned_data['is_public'])

        # Basic check that we have a valid image.
        try:
            file = BytesIO(data)
            opened = Image.open(file)
            opened.verify()
        except Exception:
            # Pillow (or PIL) doesn't recognize it as an image.
            # If a "bad" file is found we just skip it.
            # But we do flag this both in the logs and to the user.
            logger.error('Could not process file "{0}" in the .zip archive.'.format(
                filename))
            if request:
                messages.warning(request,
                                 _('Could not process file "{0}" in the .zip archive.').format(
                                     filename),
                                 fail_silently=True)
            continue

        contentfile = ContentFile(data)
        photo.image.save(filename, contentfile)
        photo.save()
        photo.sites.add(current_site)
        gallery.photos.add(photo)
        count += 1

    zip.close()

    if request:
        messages.success(request,
                         _('The photos have been added to gallery "{0}".').format(
                             gallery.title),
                         fail_silently=True)

它正在将图像名称更改为标题。 比如title_1.jpg title_2.jpg等...我想要zip文件中每个图像的初始名称 如果你可以帮助我

非常感谢

1 个答案:

答案 0 :(得分:0)

我解决了它最后,如果有人希望从我的解决方案中获益,那么代码如下所示。

def save(self, request=None, zip_file=None):
    if not zip_file:
        zip_file = self.cleaned_data['zip_file']
    zip = zipfile.ZipFile(zip_file)
    count = 1
    current_site = Site.objects.get(id=settings.SITE_ID)
    if self.cleaned_data['gallery']:
        logger.debug('Using pre-existing gallery.')
        gallery = self.cleaned_data['gallery']
    else:
        logger.debug(
            force_text('Creating new gallery "{0}".').format(self.cleaned_data['title']))
        gallery = Gallery.objects.create(title=self.cleaned_data['title'],
                                         slug=slugify(self.cleaned_data['title']),
                                         description=self.cleaned_data['description'],
                                         is_public=self.cleaned_data['is_public'])
        gallery.sites.add(current_site)
    for filename in sorted(zip.namelist()):

        logger.debug('Reading file "{0}".'.format(filename))

        if filename.startswith('__') or filename.startswith('.'):
            logger.debug('Ignoring file "{0}".'.format(filename))
            continue

        if os.path.dirname(filename):
            logger.warning('Ignoring file "{0}" as it is in a subfolder; all images should be in the top '
                           'folder of the zip.'.format(filename))
            if request:
                messages.warning(request,
                                 _('Ignoring file "{filename}" as it is in a subfolder; all images should '
                                   'be in the top folder of the zip.').format(filename=filename),
                                 fail_silently=True)
            continue

        data = zip.read(filename)

        if not len(data):
            logger.debug('File "{0}" is empty.'.format(filename))
            continue

        photo_title_root = self.cleaned_data['title'] if self.cleaned_data['title'] else gallery.title

        # A photo might already exist with the same slug. So it's somewhat inefficient,
        # but we loop until we find a slug that's available.
        while True:
            filename = filename[0:-4]
            photo_title = filename
            slug = slugify(photo_title)
            if Photo.objects.filter(slug=slug).exists():
                count += 1
                continue
            break

        photo = Photo(title=photo_title,
                      slug=slug,
                      caption=self.cleaned_data['caption'],
                      is_public=self.cleaned_data['is_public'])

        # Basic check that we have a valid image.
        try:
            file = BytesIO(data)
            opened = Image.open(file)
            opened.verify()
        except Exception:
            # Pillow (or PIL) doesn't recognize it as an image.
            # If a "bad" file is found we just skip it.
            # But we do flag this both in the logs and to the user.
            logger.error('Could not process file "{0}" in the .zip archive.'.format(
                filename))
            if request:
                messages.warning(request,
                                 _('Could not process file "{0}" in the .zip archive.').format(
                                     filename),
                                 fail_silently=True)
            continue

        contentfile = ContentFile(data)
        photo.image.save(filename, contentfile)
        photo.save()
        photo.sites.add(current_site)
        gallery.photos.add(photo)
        count += 1

    zip.close()

    if request:
        messages.success(request,
                         _('The photos have been added to gallery "{0}".').format(
                             gallery.title),
                         fail_silently=True)