TypeError:无法在Django views函数中解压不可iterable int对象

2024-04-20 11:51:00 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是URL.py、views.py和HTML页面中的代码。但是,它返回错误:TypeError:无法解压缩不可iterable int对象。

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

]

我正试图在列表视图中捕获posts blog的id,以便通过id查询从数据库中获取blog对象。下面是我的视图代码。

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)

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

有人能解释一下我做错了什么吗


Tags: path对象代码namepy视图idhome
1条回答
网友
1楼 · 发布于 2024-04-20 11:51:00

您应该在.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.pyviews.py中都是这样),因为id是一个内置函数,现在一个局部变量“隐藏”了这个内置函数。

相关问题 更多 >