Django Photologue zip upload keep images names

190 Views Asked by At

I'm working on photologue and till now it's perfect. I just want to know how can I keep the images names when uploading zip images.

Here is a the code of the save function after the zip file upload. :

   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)

It's changing the images names to the title. like title_1.jpg title_2.jpg etc ... and I want the name of the initial name of each image inside the zip file
Please If you can help me in this

Thank you very much

1

There are 1 best solutions below

0
A.H On

I solved it Finally the code became as below if one want's to get benefit from my solution for this problem .

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)