The 'img' attribute has no file associated with it django加载图片时出现的错误

参考:https://stackoverflow.com/questions/39194097/the-photo-attribute-has-no-file-associated-with-it

模板代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% for article in articles %}
    <a href="{% url 'blog:article_page' article.id %}">{{ article.title }}</a>
    <br/>
    <img src="{{ article.img.url|default_if_none:'#' }}" alt="图片打开失败" />
    <br/>
{% endfor %}
</body>
</html>

模板代码如下:

class Article(models.Model):
    title=models.CharField(max_length=32,default='Title')
    img = models.ImageField(upload_to='', max_length=100,null=True)

这种错误类似空指针异常,是某条数据的blog.img字段为空,所以在使用blog.img.url时会报错。

解决方法:在models中新建一个函数,用来判断自身的img字段是否为空,不为空则返回self.img.url。代码如下:

@property
    def img_url(self):
        if self.img and hasattr(self.img, 'url'):
            return self.img.url

猜你喜欢

转载自blog.csdn.net/swordboy_fire/article/details/81280253