ValueError: The 'cover' attribute has no file associated with it

ValueError: The 'cover' attribute has no file associated with it

我从管理面板上传了图像,它存储在 media/img 中。我想在我的 index.html 中显示发布的图像,但我得到这个 ValueError: 'cover' 属性没有与 it.I 关联的文件认为我在 url 或视图中犯了错误..我是 django 的新手。

# app urls.py

urlpatterns = [
    path('', views.PostList.as_view(), name='home'),
    path('<slug:slug>/', views.post_detail, name='post_detail'),
]
# project urls.py

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("blog.urls"), name="blog-urls"),
    path("summernote/", include("django_summernote.urls")),
]
# views.py

class PostList(generic.ListView):
    queryset = Post.objects.filter(status=1).order_by('-created_on')
    template_name = 'index.html'
    paginate_by = 3
# models.py

class Post(models.Model):
    cover = models.ImageField(upload_to='image/', default='')
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="blog_posts"
    )
    updated_on = models.DateTimeField(auto_now=True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)
<!-- index.html -->

<img src={{ post.cover.url }} alt="{{ post.title }}" width="160px" height="220px">

列表视图输出是一个查询集,意思是一个实例列表,所以你必须遍历它。

{% for post in object_list %}{% if post.cover %}
<img src={{ post.cover.url }} alt="{{ post.title }}" width="160px" height="220px">{% endif %}
{% endfor %}

也将包含 url 更改为

path("", include("blog.urls"))

没有名称,如果需要可以添加命名空间