【问题标题】:Rendering blank ImageFields in Django template在 Django 模板中呈现空白的 ImageField
【发布时间】:2018-07-26 09:25:37
【问题描述】:

我正在尝试在我的模板中呈现此模型的一个实例:

class Candidate(models.Model):
    UserID = models.ForeignKey(User, on_delete=models.CASCADE)
    ElectionID = models.ForeignKey(Election, on_delete=models.CASCADE)
    Bio = models.CharField(max_length=500, blank=True)
    Poster = models.ImageField(upload_to="profilepics/", null=True, blank=True)

我在渲染 Poster 属性时遇到了问题,如您所见,该属性可以选择为空白。

当我尝试在模板中呈现以下 html 时:

<h1>{{candidate.UserID.first_name}} {{candidate.UserID.last_name}} ({{candidate.UserID.username}})</h1>
<h2>{{candidate.ElectionID}}</h2>
<img src="{{candidate.Poster.url}}" width=240><br>

如果Poster 为空白,我会收到错误消息。

ValueError:“海报”属性没有与之关联的文件。

如何防止出现此错误?如果Poster 为空白,我不想显示任何内容,如果不是,则显然显示图像。

【问题讨论】:

标签: python html django django-templates


【解决方案1】:

使用if 条件。

<h1>{{candidate.UserID.first_name}} {{candidate.UserID.last_name}} ({{candidate.UserID.username}})</h1>
<h2>{{candidate.ElectionID}}</h2>
{% if candidate.Poster %}
    <img src="{{candidate.Poster.url}}" width=240>
{% endif %}
<br>

【讨论】:

    猜你喜欢
    • 2016-04-03
    • 2012-01-02
    • 1970-01-01
    • 2019-10-27
    • 2020-06-15
    • 2019-02-09
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多