Django:查询ImageField正在渲染所有图像

时间:2015-06-10 10:21:50

标签: python django imagefield

所以我的问题是,当我尝试查询图片网址以便将其发布到相应的帖子时,所有已上传到媒体文件夹的图片都会被呈现,即使在管理面板中它显示每个帖子都有自己的图像,并且它们被分配到不同的帖子,而不是每个帖子都为每个帖子一起呈现。

我所拥有的模型SellPost用于创建帖子和SellPostImage,用于将图像分配给帖子。

models.py

class SellPost(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=128)
    category = models.ForeignKey(Category)
    type = models.ForeignKey(SellPostType, default=None)
    body = models.CharField(max_length=400)
    price = models.DecimalField(decimal_places=1, max_digits=5, default=0.0)
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField(unique=True, default='automatic')

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(SellPost, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.title




class SellPostImage(models.Model):
    user = models.ForeignKey(User, null=True)
    post = models.ForeignKey(SellPost)
    pictures = models.ImageField(upload_to='post_images', blank=True)

    def __str__(self):
        return "{}".format(self.post)

    class Meta:
        verbose_name_plural = "Post Images"

在视图中,我尝试创建一个上下文字典(因为我是Django的新手,并且已经从Tango和Django学到了这些,所以我选择了它)用于帖子,然后是图像:

views.py

def post(request, post_name_slug):

    context_dict = {}
    try:
        post = SellPost.objects.get(slug=post_name_slug)
        context_dict['post'] = post

        post_image = SellPostImage.objects.all()
        context_dict['post_image'] = post_image

    except SellPost.DoesNotExist:
        pass

    return render(request, 'p.html', context_dict)

以下是我尝试在HTML文件中呈现它们的方法。

p.html

 <ul>
        {% for post in posts %}
        <li><a href="/p/{{ post.slug }}">{{ post.title }}</a> </li>
        {% for post_images in post_image %}

        <img style="width:200px; height:200px;" src="{{ post_images.pictures.url }}" />

    {% endfor %}
        {% endfor %}
    </ul>

2 个答案:

答案 0 :(得分:1)

post方法中查询所有SellPostImage s:

post_image = SellPostImage.objects.all()

这就是为什么你得到每个帖子的所有图像。

您可以通过执行以下操作来仅过滤与帖子关联的图片:

post_image = SellPostImage.objects.filter(post=post)

它将提供该特定帖子的所有图像。

答案 1 :(得分:1)

您想要为检索到的帖子过滤SellPostImage

post = SellPost.objects.get(slug=post_name_slug)
context_dict['post'] = post

post_image = SellPostImage.objects.filter(post=post)
context_dict['post_image'] = post_image

但您可以轻松地将逻辑部分直接放入模板中:

 {% for post in posts %}
    <li><a href="/p/{{ post.slug }}">{{ post.title }}</a> </li>
    {% for post_images in post.sellpostimage_set.all %}
      <img style="width:200px; height:200px;" src="{{ post_images.pictures.url }}" />
    {% endfor %}
{% endfor %}

然后您可以删除视图中的SellPostImage:

try:
    post = SellPost.objects.get(slug=post_name_slug)
    context_dict['post'] = post
except SellPost.DoesNotExist:
    pass