【发布时间】:2020-05-06 11:24:28
【问题描述】:
所以我有以下型号:
class Image(models.Model):
image=models.ImageField(upload_to='postimages')
id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
class Post(models.Model):
title=models.CharField(max_length=500)
created_date=models.DateField(auto_now=True)
id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
images=models.ManyToManyField(Image)
user=models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, related_name='posts')
在我看来,我创建了一个这样的帖子对象:
post=Post(title=title)
post.save()
post.images.add(image)
现在我需要在我的主页中显示 Image 模型的图像字段。我正在尝试这样做:
{%for post in posts%}
<img src="{{post.images.image}}">
{%endfor%}
但这会返回 src=(unknown) 的图像。所以我的问题是如何访问 Image 模型的 image 字段?
编辑: 这是我的views.py
def addpost(request):
imageform=ImageForm()
postform=PostForm()
if request.method=="POST":
imageform=ImageForm(request.POST, request.FILES)
postform=PostForm(request.POST)
if imageform.is_valid() and postform.is_valid():
#add the image and the post to the database
image=Image(image=request.FILES['image'])
image.save()
title=request.POST['title']
post=Post(title=title)
post.save()
post.images.add(image)
return redirect('../')
还有我的表格:
<form method="post" action="{%url 'addpost'%}" enctype="multipart/form-data">
{%csrf_token%}
{{imageform}}
{{postform}}
<button type="submit">Post</button>
</form>
【问题讨论】:
-
src=(unknown) or src=""?
-
好吧,当我在 html 中检查我的页面时,有
-
你能在views.py中向我们展示完整的渲染功能吗?你的数据库中有关于图像的数据吗?我的意思是你的 views.py 工作吗
-
我在帖子中添加了 views.py 和 home.html。如何检查 views.py 是否正常工作?当我做 print(Image.objects.all()) 我得到一个 QuerySet 所以我假设它正在工作。
标签: django many-to-many field