【问题标题】:Django: Upload multiple directory of images at onceDjango:一次上传多个图像目录
【发布时间】:2021-11-05 00:45:18
【问题描述】:

在我的 Django 项目中,我想从目录目录上传产品的批量图像。每个目录都以产品的 SKU 命名。每个目录中可能有也可能没有多个图像。我怎样才能实现这个功能?

我的模特:

class Product(models.Model):
    sku = models.CharField('SKU', max_length = 200)
    name = models.CharField('Name', max_length = 1000)
    price = models.CharField('Price', max_length = 200)
    quantity = models.CharField('Quantity', max_length = 200)

    class Meta:
        verbose_name = 'Product'
        verbose_name_plural = 'Products'

    def __str__(self):
        return self.name

class Image(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='product_image')
    image = models.ImageField(upload_to='images/')

    class Meta:
        verbose_name = 'Image'
        verbose_name_plural = 'Images'

    def __str__(self):
        return str(self.image)

我的 urls.py

from django.urls import path
from . import views

urlpatterns = [

    path('products/', views.products, name="products"),
    path('products_import/', views.products_import, name="products_import"),    
]

我的意见.py

def products_import(request):
    heading = 'Upload Products'
    info = '''This importer will import the following fields: sku, name, price, quantity from a csv file.'''
    if request.method == 'POST':
        paramFile = io.TextIOWrapper(request.FILES['file'].file, encoding='latin-1')
        product = csv.DictReader(paramFile)
        list_of_dict = list(product)
        objs = [
            Product(
                sku=row['sku'],
                name=row['name'],
                price=row['price'],
                quantity=row['quantity'],
         )
         for row in list_of_dict
        ]
        record_count = len(list_of_dict)
        try:
            msg = Product.objects.bulk_create(objs)
            messages.success(request, str(record_count) + ' records were uploaded.')
            return redirect('products_import')
        except Exception as e:
            error_message = 'Error While Importing Data: ',e
            messages.error(request, error_message, e)    
            return redirect('products_import')
    context = {'heading': heading, 'info': info}
    return render(request, 'coreapp/product/products_import.html', context)

我可以使用下面的 CSV 和上面的视图上传批量产品。

下面的每个 SKU 文件夹中有多个图像。

我想立即上传文件夹中的图片并将它们与各自的 SKU 链接。我该如何实现?任何指导将不胜感激。

注意:我可以为产品上传一张图片。如果我们要上传数千个产品及其相关图片,上传单张图片是不可行的。

【问题讨论】:

    标签: django file-upload


    【解决方案1】:

    手动将图像复制并粘贴到 MEDIA_ROOT + '/images' 目录下。

    使用自定义命令而不是视图。在这种情况下,它将更加有用和舒适。这里有一个link 怎么做。

    命令的主要部分如下所示。

    import os
    from django.conf.settings import MEDIA_ROOT
    
    
    ...
    
    for data in products_data:
        product = Product.objects.create(sku=data['sku'], ...)
        images = os.listdir(os.path.join(MEDIA_ROOT, 'images'))
        for image in images:
            Image.objects.create(
                product=product,
                image=f'images/{product.sku}/image'
            )
    

    确保images目录下除了images之外没有任何文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 2015-06-14
      • 2017-04-12
      • 1970-01-01
      • 2021-12-07
      • 2018-12-11
      相关资源
      最近更新 更多