0

I'm building an inventory list that includes the fields listed below in my Django model. I have a folder full of images that the name of the images correspond to the the Item Number. For install, the item number may be 4119, then the image file name will be 4119.jpg.

I would like to write a script that iterated over the items in the database and uploads the corresponding image. Any thoughts on where to start are greatly appreciated.

from django.db import models

def directory_path(instance, filename):
    return '{0}/{1}/{2}'.format(supplier.name, pricelist.item_number, filename)

class Supplier(models.Model):
    name = models.CharField(max_length=80)

    def __str__(self):
        return self.name

class PriceList(models.Model):
    supplier = models.ForeignKey('Supplier', on_delete=models.CASCADE)
    item_number = models.CharField(max_length=80)
    description = models.CharField(max_length=120)
    case_quantity = models.CharField(max_length=80)
    piece_list_amount = models.CharField(max_length=80)
    partner_list_amount = models.CharField(max_length=80)
    upload = models.ImageField(upload_to=directory_path)


    def __str__(self):
        return self.item_number
joshlsullivan
  • 1,375
  • 2
  • 14
  • 21

1 Answers1

0

You can look at my code and implement exactly what you need ... I hope this will be helpful for you:

import os
from Project.settings import BASE_DIR
from apps.showcase.models import Product
from django.core.files import File

obj_id_to_img_filename_mapping = (
    (175, 'full_ef58c1a5af252d4459055481b1bbfa76.jpg'),
    (176, 'full_2111856a6a092a3c65639aff56070aef.jpg'),
    (177, 'full_b8154e9b348561ee295c2d1651ecca3c.gif'),
    # ...
)


def update_product_images():
    print('Starting upload products images...\n')
    for product_id, file_name in obj_id_to_img_filename_mapping:
        if file_name:
            product = Product.objects.get(pk=product_id)

            absolute_filename = os.path.join(BASE_DIR, 'apps/showcase/static/showcase/images/initial_data/product', file_name)
            local_file = open(absolute_filename, 'r')
            django_file = File(local_file)

            product.image.save(file_name, django_file, save=True)

            print(absolute_filename + '\n')
madzohan
  • 11,488
  • 9
  • 40
  • 67
  • My app has a folder of jpgs, so how would I match 4119.jpg to the 4119 items in the database? – joshlsullivan Sep 26 '16 at 00:42
  • Just filter by `item_number` instead of get object by `pk` in this example ... If you are new to Django - please complete official tutorial :) – madzohan Sep 27 '16 at 19:50