我正在尝试制作一个django
电子商务应用,其中的产品有不同的变化。例如,产品T恤有不同的颜色(红色,绿色......)。对于每个变体,我想上传至少三个不同的图像。目前,我每个版本只能上传一张图片。
我的应用代码:
class Product(models.Model):
title = models.CharField(max_length=120)
price = models.DecimalField(decimal_places=2, max_digits=20)
default_image = models.ImageField(upload_to=image_upload_to_prod, blank=True, null=True)
slug = models.SlugField(blank=True, null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('Products:SingleProduct', kwargs={'pk': self.pk})
class Variation(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
title = models.CharField(max_length=120)
price = models.DecimalField(decimal_places=2, max_digits=20)
DEFAULT = 'DEFAULT'
RED = 'RED'
BLUE = 'BLUE'
TYP = (
(DEFAULT, 'DEFAULT'),
(RED, 'RED'),
(BLUE, 'BLUE'),
)
color = models.CharField(max_length=100, choices=TYP, default=DEFAULT)
image = models.ImageField(upload_to=upload_location, blank=True, null=True)
def get_price(self):
if self.sale_price is not None:
return self.sale_price
else:
return self.price
def get_image(self):
if self.image is not None:
return self.product.default_image
else:
return self.image
def get_absolute_url(self):
return self.product.get_absolute_url()
def upload_location(object, filename):
title = object.product.title
slug = slugify(title)
return "products/%s" % (slug)
如何添加多个图像并在模板中显示它们?
答案 0 :(得分:0)
更新模型并使用单独的图像类
class ProductImage(models.Model):
image = models.ImageField(upload_to=image_upload_to_prod, blank=True, null=True)
class Product(models.Model):
title = models.CharField(max_length=120)
price = models.DecimalField(decimal_places=2, max_digits=20)
default_image = models.ForeignKey(ProductImage)
slug = models.SlugField(blank=True, null=True)