简体   繁体   English

在 Django 模板中渲染空白 ImageFields

[英]Rendering blank ImageFields in Django template

I am trying to render an instance of this model in my template:我正在尝试在我的模板中呈现此模型的实例:

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)

I am having trouble with rendering the Poster attribute which, as you can see, has the option of being blank.我在渲染海报属性时遇到问题,如您所见,可以选择为空白。

When I try to render the following html in the template:当我尝试在模板中呈现以下 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>

I get an error if Poster is blank.如果Poster为空白,我会收到错误消息。

ValueError: The 'Poster' attribute has no file associated with it. ValueError:“海报”属性没有与之关联的文件。

How do I prevent this error?如何防止此错误? I want to show nothing if Poster is blank and obviously show the image if it isn't.如果Poster是空白的,我不想显示任何内容,如果不是,则显然显示图像。

Use an if condition.使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM