【问题标题】:ValueError: The 'cover' attribute has no file associated with itValueError:“封面”属性没有与之关联的文件
【发布时间】:2020-08-11 23:57:54
【问题描述】:

我从管理面板上传了图片,它存储在 media/img 中。我想在我的 index.html 中显示发布的图片,但我得到了这个 ValueError:'cover' 属性没有与之关联的文件。我想我我在 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">

【问题讨论】:

  • post.cover.image.url 工作吗?

标签: django django-models django-views django-templates django-urls


【解决方案1】:

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

{% 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"))

没有名字,如果你想你可以添加一个命名空间

【讨论】:

    猜你喜欢
    • 2023-02-21
    • 2021-02-11
    • 2020-03-08
    • 1970-01-01
    • 2016-02-06
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    相关资源
    最近更新 更多