TypeError:无法在Django视图函数中解压缩不可迭代的int对象

jef*_*eff 6 python django django-urls django-views

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

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

]

我正在尝试在列表视图中捕获帖子博客的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)
Run Code Online (Sandbox Code Playgroud)

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

有人可以解释我在做什么错

Wil*_*sem 6

您应该在.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)
Run Code Online (Sandbox Code Playgroud)

我还建议将变量重命名为其他变量(在urls.py和中都重命名views.py),因为id它是内置函数,现在局部变量正在“隐藏”该内置函数。