【发布时间】:2018-04-10 06:41:08
【问题描述】:
我有一个表单,允许用户上传图片和图片网址。根据他们在页面上使用的图像 src 应该是上传的图像,或者来自 URL 的图像。
这是表格:
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url']
labels = {
'name': 'Product Name',
'url': 'Product URL',
'product_type': 'Product Type',
'description': 'Product Description',
'image': 'Product Image',
'image_url': 'Product Image URL',
'price': 'Product Price'
}
widgets = {
'description': Textarea(attrs={'rows': 5}),
}
我有两个问题需要解决。第一个是,在需要显示图像的页面上,我有以下内容:
<img class="img-fluid" {% if product.image.url %}src="{{ product.image.url }}" {% else %} src="{{ product.image_url }}" {% endif %} alt="" />
仅显示“product.image.url”图像。我想我在这里让自己感到困惑,所以我寻求帮助。
第二件事是只允许用户上传和图像或使用图像 URL - 列表中的下一个,但现在,我想弄清楚如何解决这个问题。
【问题讨论】:
-
product.image_url 的 src 是否为空?
-
到目前为止,要么是 image.url 要么是 image_url - 不是两者都有 - 这有意义吗?
-
我只是不明白这个问题。你的意思是product.image_url值没有出现在html中还是出现了但是图片没有显示?
-
如果存在图像 (product.image.url),它会从 /static/images 文件夹中提取图像并在页面上显示图像。如果没有图像,则应该显示图像 URL,这是图像的外部链接 (product.image_url),如果存在。
标签: django forms model display