Source

gnocchi-catalogue / catalogue / management / commands / sync_product_images.py

from django.core.management.base import NoArgsCommand
from gnocchi_catalogue.models import Product, ProductImage
from django.conf import settings
from glob import glob
import os.path

class Command(NoArgsCommand):
    help = "Ensure an Image entry exists for all files in images/ directory"

    def handle_noargs(self, **options ):
        root_path = os.path.join( settings.MEDIA_ROOT, 'images/products/' )

        pfx = len(settings.MEDIA_ROOT)
        for product in Product.objects.all():
            print "Product: %s" % product
            prod_path = os.path.join( root_path, str(product.id), '*' )
            print "Searching: %s" % prod_path
            for filename in glob( prod_path ):
                filename = filename[pfx:] # strip media path
                print "Found: %s" % filename
                if not product.productimage_set.filter( image=filename ).count():
                    print "[%s] Adding Image: %s" % ( product, filename, ),
                    try:
                        ProductImage.objects.create(
                            product=product,
                            image=filename,
                            order=1
                        )
                    except:
                        print " Failed!"
                    else:
                        print " Done!"
        print "Done."
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.