【问题标题】:Django {% if %} statementDjango {% if %} 语句
【发布时间】: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


【解决方案1】:

如果您只想显示图像的外部链接而不是图像本身,那么您可以:

{% if product.image.url %}
<img class="img-fluid" src="{{ product.image.url }}" alt="" />
{% else %} 
   {% if product.image_url %}
      <a href="{{ product.image_url }}">{{ product.image_url }}</a>
   {% else %}
      <a href="">{{ product.image_url }}>Sorry, no link for image!</a>
   {% endif %}
{% endif %}

【讨论】:

  • 谢谢 - 但关键是,如果本地图像不可用 } 则外部图像被拉入 。现在,用户可以上传图片并输入外部图片 url - 一旦我解决了这个问题,我将输入只能使用一个的逻辑。
  • 对不起,但是对于不同的 cmets,您自相矛盾,这就是为什么我不清楚问题的原因
  • 可能您没有注意到我的代码中没有 src={{product.image_url}}?
  • 我再说一遍同样的事情——如果没有本地 img,它会寻找远程图像——你的代码和我的完全一样。
  • 它没有,但没关系。考虑再逐行检查一次。在我看来,这正是您在上一个问题评论中描述的逻辑。
猜你喜欢
  • 2023-03-16
  • 2018-08-05
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2013-10-17
  • 1970-01-01
  • 2015-02-13
相关资源
最近更新 更多