这是我在models.py中创建的类。
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
vendor = models.ForeignKey(Vendor, related_name='products', on_delete=models.CASCADE,blank=True,null=True)
name = models.CharField(max_length=255)
slug = models.SlugField()
description = models.TextField(blank=True, null=True)
price = models.DecimalField(max_digits=6, decimal_places=2)
vegetarian = models.BooleanField(default='True')
created_at = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='uploads/',blank=True,null=True)
thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True)
class Meta:
ordering = ('-created_at',)
def __str__(self):
return self.name
def get_thumbnail(self):
if self.thumbnail:
return self.thumbnail.url
else:
if self.image:
self.thumbnail = self.make_thumbnail(self.image)
self.save()
return self.thumbnail.url
else:
return 'https://https://via.placeholder.com/240x180.jpg'
def make_thumbnail(self, image, size=(300, 200)):
img = Image.open(image)
img.convert('RGB')
img.thumbnail(size)
thumb_io = BytesIO()
img.save(thumb_io, 'JPEG', quality=85)
thumbnail = File(thumb_io, name=image.name)
return thumbnail
字符串
这是我的forms.py
from django.forms import ModelForm
from product.models import Product
class ProductForm(ModelForm):
class Meta:
model = Product
fields = ['category','image','name','description','price']
型
这是我的HTML文件:
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<div class="field">
<div class="control">
<button class="button is-dark is uppercase">Submit</button>
</div>
</div>
</form>
型
但是当我运行服务器时,我无法看到我的产品的图像,而我可以看到我想要的其他细节,如frontpage.html文件所示:
{% for product in products %}
<li>{{product.name}}</li>
<li>{{product.price}}$</li>
<li>{{product.description}}</li>
<li><figure><img src="{{ product.get_thumbnail }}"></figure></li>
{% endfor %}
型
请解释一下为什么?我也想在我的首页上看到图片。当我填写表单添加产品时,我上传图像并填写其他详细信息,但只有文本详细信息可见,而不是图像。
1条答案
按热度按时间jrcvhitl1#
尝试将
multipart/form-data
添加到字符串