2016-08-26 2 views
0

Я работаю над фотологом, и до сих пор это прекрасно. Я просто хочу знать, как сохранить имена изображений при загрузке zip-изображений.Django Photologue zip upload сохранить названия изображений

Вот код функции сохранения после загрузки файла 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 и т.д ... и я хочу, чтобы имя исходного имени каждого изображения внутри архива
Пожалуйста, если вы можете помочь мне в этом

Большое спасибо

+0

Не могли бы вы добавить код и показать нам, что вы делали до сих пор? – n2o

+0

Я не изменил концепцию фотолога. Я просто расширил некоторые модели для удовлетворения моих потребностей. Это модель сохранения в zip-файле –

+0

. Пожалуйста, добавьте этот код к вашему вопросу и отступьте его ;-) – n2o

ответ

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) 
Смежные вопросы