【问题标题】:How can I use the value of a model atributte inside a <img> src?如何在 <img> src 中使用模型属性的值?
【发布时间】:2021-12-20 07:33:33
【问题描述】:

我正在尝试创建一个项目,其中模型属性用作图像名称的一部分。我尝试了很多方法,我认为我接近解决方案,但我有一个问题。这是我的代码:

<img src="{% static 'media/{{model.atributte}}.jpg' %}"  alt="{% static 'media/{{model.atributte}}.jpg' %}"></img>

例如:如果属性的值为“img”,这应该导致 = static/media/img.jpg 我的意图是使用它来设置 src 路径,但 this is the result 我进入了 HTML。

/static/media/%7B%7Bmodel.atribute%7D%7D.jpg

感谢任何形式的帮助或建议,作为额外的评论,我想澄清一下,如果我在 src 中写入属性的值,它确实会找到图像,但总是会为同一个模型做这件事,我有几个模型。提前致谢。

【问题讨论】:

  • 您是否尝试过将模型属性单独添加到视图的上下文中?还是您的 html 中有很多图片要显示?
  • 我有很多图片,每个模型实例至少一张。

标签: html django django-models


【解决方案1】:

如果您在开发过程中让 Django 提供媒体文件,而在生产过程中让网络服务器(如 Apache、Nginx 等)提供媒体文件,则可以使用 .url 属性:

&lt;img src="{{ model.atributte<strong>.url</strong> }}"  alt="{{ model.atributte<strong>.url</strong> }}"&gt;

有关详细信息,请参阅serving files uploaded by a user during development section of the documentation

【讨论】:

    猜你喜欢
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多