ValueError:'cover'属性没有与之关联的文件

问题描述 投票:0回答:1

我从管理面板上传了图片,并将其存储在media / img中。我想在我的index.html中显示发布的图片,但出现此ValueError:'cover'属性没有与之关联的文件。我想我是在网址或视图中犯错误..我是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">
django django-models django-views django-templates django-urls
1个回答
0
投票

列表视图输出是一个查询集,表示实例列表,因此您必须遍历它。

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

也将包含网址更改为

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

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

© www.soinside.com 2019 - 2024. All rights reserved.