以下是我在 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.py
和 views.py
中),因为 id
是一个内置函数,现在一个局部变量“隐藏”了这个内置函数。
关于python - 类型错误 : cannot unpack non-iterable int object in Django views function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242684/