【问题标题】:Django TypeError objects is not iterableDjango TypeError 对象不可迭代
【发布时间】:2019-07-25 02:50:36
【问题描述】:

我尝试在 django 的 html 模板中显示模型数据。

我的模特:

class Author(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField(blank=True, null=True)
    date_of_death = models.DateField(blank=True, null=True)

    def get_absolute_url(self):
        return reverse('author_detail', args=[str(self.id)])

    class Meta():
        ordering = ['first_name', 'last_name']

    def __str__(self):
        return f'{self.first_name} {self.last_name}'

我的观点:

def author_detail_view(request, pk):
    author = get_object_or_404(Author, pk=pk)
    return render(request, 'author_detail.html', context={'author_detail': author})

我的网址:

 path('author/<int:pk>', views.author_detail_view, name='author_detail')

And My Templates View:
{% extends 'base.html' %}

{% block content %}
<h1>Author Detail</h1>
    {% for author in author_detail %}
<ul>
    <li>Name: {{ author.first_name }} {{ author.last_name }}</li>
    <li>Date of Birth: {{ author.date_of_birth }}</li>
</ul>
    {% endfor %}
{% endblock %}

但问题是,它显示错误:

/author/2 处的类型错误

“作者”对象不可迭代

请求方法:GET 请求网址:http://127.0.0.1:8000/author/2 Django 版本:2.1.5 异常类型:TypeError 异常值:

“作者”对象不可迭代

异常位置:/home/pyking/.local/lib/python3.6/site-packages/django/template/defaulttags.py 在渲染中,第 165 行 Python 可执行文件:/usr/bin/python3 Python 版本:3.6.7

【问题讨论】:

  • 您的author_detail 是一个单个 Author 对象,因此使用{% for author in author_detail %} 没有多大意义。

标签: python django


【解决方案1】:

author_detail 是一个单个 Author 对象,因此迭代它没有意义。您可以迭代哪些元素?

你可以这样渲染它:

{% extends 'base.html' %}

{% block content %}
<h1>Author Detail</h1>
<ul>
    <li>Name: {{ author_detail.first_name }} {{ author_detail.last_name }}</li>
    <li>Date of Birth: {{ author_detail.date_of_birth }}</li>
</ul>
{% endblock %}

【讨论】:

    猜你喜欢
    • 2020-02-28
    • 2021-06-09
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2013-09-01
    • 2017-08-27
    • 2018-10-10
    • 2021-12-13
    相关资源
    最近更新 更多