Django Uplaod并显示多个图像

这是我的模型帖子,我想在该帖子中为多张特定图片张贴多张图片,因此我创建了从PostPicture到Post的外键。

            class Post(models.Model):
                title = models.CharField(max_length=200,unique=True)
                # image = models.FileField(null = True,blank=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)
                #code for Thumbnail
                # image = models.ImageField(upload_to = "media",default='DEFAULT VALUE')
                image_thumbnail = ProcessedImageField(upload_to = "thumbnail",processors = [ResizeToFill(100,50)],format = 'JPEG',options = {'quality':60},default='DEFAULT VALUE')

           class Meta:
            ordering = ['-created_on']

           def __str__(self):
            return self.title

          #code for uploading multiple images
             class PostPicture(models.Model):
               picture =models.ImageField(upload_to="blog_images",blank=True)
               postid =models.ForeignKey(Post,on_delete=models.CASCADE,related_name='pictures')  

这是我的模板代码,我在其中循环浏览图片并尝试显示它们。

          {% for i in post.pictures.all %}

              <img src =  "{{ post.pictures.url }}" height = "200",width="200"/>


          {% endfor %}

这是views.py


    def post_detail(request,slug):
        template_name = 'post_detail.html'
        post = get_object_or_404(Post,slug=slug)
        comments = post.comments.filter(active=True)
        new_comment = None
        # Comment posted
        if request.method == 'POST':
            comment_form = CommentForm(data=request.POST)
            if comment_form.is_valid():

                # Create Comment object but don't save to database yet
                new_comment = comment_form.save(commit=False)
                # Assign the current post to the comment
                new_comment.post = post
                # Save the comment to the database
                new_comment.save()
        else:
            comment_form = CommentForm()

        return render(request,template_name,{'post': post,'comments': comments,'new_comment': new_comment,'comment_form': comment_form}
                                               )


我正在使用admin添加博客文章,并附加ss来查看管理员。![ ] 1

这是UI上的输出,我没有在此处显示图像。

Django Uplaod并显示多个图像

我还在添加目录的屏幕快照:

Django Uplaod并显示多个图像

谁能帮助我,我哪里出问题了

qjf6835466qq 回答:Django Uplaod并显示多个图像

模板不正确。

您在for循环内为src使用了错误的变量:

          {% for i in post.pictures.all %}

              <img src =  "{{ i.picture.url }}" height = "200",width="200"/>


          {% endfor %}
本文链接:https://www.f2er.com/2866461.html

大家都在问