【发布时间】: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