python - 类型错误 : cannot unpack non-iterable int object in Django views function

标签 python django django-views django-urls

以下是我在 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'),

]

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

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)

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

谁能解释一下我做错了什么

最佳答案

您应该在 .filter(…) [Django-doc] 中指定参数名称或 .get(…) [Django-doc]调用:

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

   return render(request, template, context)

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

关于python - 类型错误 : cannot unpack non-iterable int object in Django views function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242684/

相关文章:

Django:在 POST 和 GET 中访问上下文数据

python - django 模板 : how to expand a variable into the string argument for the built-in tag `url`

python - 如何打印 groupby 对象

python - 谷歌云语音到 Python 中的文本 : Save translation and time to JSON

python - 如何使用 Python 将 'NULL' 值插入 PostgreSQL 数据库?

python - Mysql 不从 Aqua data studio 或 Django 返回现有行

python - 将单选按钮与 Django 中的表行关联

python - Django Rest Framework Api 查看 GET

python - 如何从数据库中获取最近 24 小时的记录

python - 无法在 Ubuntu 上为 pypy 安装 pip