【问题标题】:TypeError: cannot unpack non-iterable int object in Django views functionTypeError:无法在 Django 视图函数中解压不可迭代的 int 对象
【发布时间】:2019-04-14 00:34:56
【问题描述】:

以下是我在 URL.py、views.py 和 HTML 页面中的代码。但是,它返回错误:TypeError: cannot unpack non-iterable int object。

urlpatterns = [
    path('', views.blogs_home, name='blogs'),
    path('<int:id>', views.single_blog, name='detailed_view'),

]

我正在尝试在列表视图中捕获帖子博客的 id,以使用 id 查询从数据库中获取博客对象。以下是我的视图代码。

def single_blog(request,id):
   blog_single = Blogs.objects.get(id)
   context = {'blog_single': blog_single}
   template = 'blog_home.html'

   return render(request, template, context)

但是,正如我所提到的,它返回上述错误。

谁能解释我做错了什么

【问题讨论】:

    标签: python django django-views django-urls


    【解决方案1】:

    您应该在.filter(..) 或.get(..) 调用中指定参数的名称:

    def single_blog(request, id):
       blog_single = Blogs.objects.get(id=id)
       context = {'blog_single': blog_single}
       template = 'blog_home.html'
    
       return render(request, template, context)

    我还建议将您的变量重命名为其他名称(因此在urls.py 和views.py 中),因为id 是一个内置函数,现在一个局部变量正在“隐藏”这个内置函数。

    【讨论】:

    • 谢谢你,Willem 和你的建议。谢谢,伙计。
    • 你好威廉。我已将 urls.py 和 views.py 中的 id 更改为 post_id。但是,出现了一个新错误——“detailed_view”的反向,没有找到任何参数。尝试了 1 种模式:['blogs/(?P[0-9]+)$']
    • @jeff:这可能是因为有一个{% url ... %} 和id=...,而不是post_id=...。
    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 2020-07-21
    • 2021-11-01
    • 2021-06-06
    • 2020-01-28
    • 2019-04-22
    • 2020-04-08
    • 2021-05-25
    相关资源
    最近更新 更多