Uploading images from BaseCommand

I am attempting to bulk upload product information from a csv file and product images from another folder. csv upload works correctly but the product image only saves the filname. It doesn’t save it to the media folder (or aws s3 in production) - only the filename. I believe that this would be ok if I dropped the images into the media folder (or S3) but the images are in 1700 different folders. Please help!

class Command(BaseCommand):
help = 'Load a products csv file into the database'


def handle(self, *args, **kwargs):

    with open('fb_django/products/management/commands/django_product_data.csv', 'r') as f:
        reader = csv.reader(f, dialect='excel')
        user = User.objects.get(username='admin')
        for row in reader:
            try:
                images_folder = row[2]
                images_path = "fb_django/products/management/commands/images1/"
                path = os.path.join(images_path, images_folder)
                for image in os.listdir(path):
                    filename = os.fsdecode(image)
                    if filename.endswith("1.jpg"):
                        image_main = image
            except FileNotFoundError:
                    continue

            if image_main:        
                try:
                    print(row[0])
                    product = Product.objects.create(
                        sku=row[0],
                        supplier_category=row[1],
                        supplier_price=row[3],
                        title=row[4],
                        description=row[5],
                        image_main=image_main,                   
                        created_by=user
                    )
                except IntegrityError:
                    continue
                except ValidationError:
                    continue
            else:
                print("didn't work")

When you’re working with the content of a FileField, you need to use a File object to represent it.

So instead of just referencing the file name (image_main = image), it’ll be something more like image_main = File(image). (There may be - or probably will be - more to this than that, but that’s the basic idea.)

1 Like