【问题标题】:Django access fields of model with many to many relationshipDjango访问具有多对多关系的模型字段
【发布时间】: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


【解决方案1】:

我找到了解决方法。在我的 html 中,我调用了 {{post.images.image}}。相反,我需要调用 {{post.images.all}} 来获取所有图像模型,然后为每个我需要获取图像的模型。所以不是

{%for post in posts%}
    <img src="{{post.images.image}}">
    <p>{{post.title}}</p>
{%endfor%}

我需要做的

{%for post in posts%}
    {%for image in post.images.all%}
        <img src="{{image.image}}">
    {%endfor%}
    <p>{{post.title}}</p>
{%endfor%}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2020-07-01
    • 2014-05-16
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多