在Django博客主页上显示图片URL



我无法在登录页上加载我的博客图像。请任何人都能解决这个问题。

循环内部的HTML代码:

{% for item in object_list %}

<img class="rounded" src="{{item.main_image.url}}">

它会出错"main_image"属性没有与其关联的文件。

我可以通过简单地这样做来加载详细页面中的图像:

src="{{object.main_image.url}}">

我的型号:

class Item(models.Model):
title = models.CharField(max_length=100)
description= RichTextField(blank=True, null=True)
main_image= models.ImageField(null=True, blank=True,upload_to='images/')
date = models.DateTimeField(auto_now_add=True)
item_slug = models.CharField(max_length=200, default=1)
item_category = models.ForeignKey(Categories, default=1, on_delete=SET_DEFAULT)

因为您的图像是可选的,所以在尝试访问它之前,您需要检查图像是否存在,因为虽然它不存在,但它没有URL。

要做到这一点,请在访问模板之前进行检查;

{% if item.main_image %}
<img class="rounded" src="{{ item.main_image.url }}">
{% else %}
<p>No image</p>
{% endif %}

最新更新