【问题标题】:'Post' object is not iterable:TypeError'Post' 对象不可迭代:TypeError
【发布时间】:2020-03-27 05:41:50
【问题描述】:

这是我的看法。我使用基于函数的视图来显示帖子的详细信息。

def post_detail(request,slug,pk):
    detail = get_object_or_404(Post,slug=slug,pk=pk)
    context={
        'detail':detail
    }
    return render(request,'post/post_detail.html',context)

这是我的网址。的 post_detail ,它的名字也是 post_detail

path('<int:pk>/<str:slug>/', views.post_detail, name='post_detail'),

这是我的模型。这是一个帖子模型,我有 get_absolute_url () 来渲染到详细视图

class Post(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(User,on_delete=models.SET_NULL,null=True)
    story= models.TextField()
    image= models.ImageField()
    slug = models.SlugField()

    def get_absolute_url(self):
        return reverse('post_detail',kwargs={'pk':self.pk,'slug':self.slug})

    def __str__(self):
        return self.title

这是我的 post_detail 视图的 post/post_detail.html

 {% extends "post/base.html" %}
 {% block content %}
 {% for posts in detail %}
 {{posts.image.url}}
 {{posts.title}}
 Written by: {{posts.author}}

{% endfor %}

 {% endblock content %}

【问题讨论】:

    标签: python django templates model


    【解决方案1】:

    在您的详细信息模板中,您不需要for 循环;因为您只是将 一个 帖子传递给模板:

    {% block content %}
    
    {{detail.image.url}}
    {{detail.title}}
    
    Written by: {{detail.author}}
    {% endblock content %}
    

    【讨论】:

      猜你喜欢
      • 2013-09-01
      • 2017-08-27
      • 2018-10-10
      • 2021-12-13
      • 2019-02-20
      • 2018-12-12
      • 2018-07-16
      • 2011-09-12
      • 2018-04-14
      相关资源
      最近更新 更多