【发布时间】: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