Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mrchrisadams/42a6dda97a88516de01e54153d67ae4c to your computer and use it in GitHub Desktop.
Save mrchrisadams/42a6dda97a88516de01e54153d67ae4c to your computer and use it in GitHub Desktop.
A few functions I've used for importing photos that were previously in a huge mess of nested folders
#!/usr/bin/env python
import os
from django.conf import settings
from django.core.files.images import ImageFile
from wagtail.wagtailimages.models import Image as WagtailImage
import dimensions
import glob2
def check_files_in_dir(dir_path, min_width=300):
images = []
for path in glob2.glob(dir_path):
result = check_valid_file(path, min_width)
if result['ok']:
images.append(path)
return images
def check_valid_file(path, min_width=300):
try:
dims = dimensions.dimensions(path)
if dims[0] > min_width:
return {'ok': True, 'path': path}
else:
return {'ok': False, 'path': path, 'type': 'image'}
except NotImplementedError:
return {'ok': False, 'path': path, 'type': 'doc'}
except IOError:
return {'ok': False, 'path': path, 'type': 'dir'}
def create_wagtail_image_from_file(path):
friendly_name = nice_name_from_path(path)
wi = WagtailImage.objects.filter(title=friendly_name).first()
# if we have it already, we exit early
if wi:
return {'image': wi, 'status': 'dupe'}
# otherwise, create it
wi = WagtailImage()
wi.title = nice_name_from_path(path)
img_path = os.path.join(settings.MEDIA_ROOT, path)
wi.file = ImageFile(open(img_path, 'r'), name=path.split('/')[-1])
wi.height = wi.file.height
wi.width = wi.file.width
wi.save()
wi.tags.add(u"org-import")
wi.save()
return {'image': wi, 'status': 'new'}
def nice_name_from_path(img_path):
filename = img_path.split('/')[-1]
name, dot, extension = filename.rpartition('.')
return name.replace('_', ' ')
def import_image_for(model_instance, path, imagefield="image"):
"""
Accepts a model instance, and a path string, then tries to attach Wagtail
image to it, creating it if there isn't already one for file at `path`.
"""
wi = create_wagtail_image_from_file(path)
model_instance = add_image_to_model(model_instance, wi['image'], imagefield=imagefield)
return model_instance
def add_image_to_model(model, image, imagefield="image"):
"""
Accepts a model instance, and a wagtail image, and
adds the image to the model instance
"""
setattr(model, imagefield, image)
model.save()
return model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment