类型错误:无法在 Django 视图函数中解压不可迭代的 int 对象 [英] TypeError: cannot unpack non-iterable int object in Django views function
问题描述
以下是我在 URL.py、views.py 和 HTML 页面中的代码.但是,它返回了错误:TypeError: cannot unpack non-iterable int object.
Following is my code in URL.py, views.py and HTML page. However, it returns me the error: 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 查询从数据库中获取博客对象.以下是我的查看代码.
I am trying to capture the id of posts blogs in the list view to get the blog object from the database with id query. Following is my view code.
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)
但是,正如我所提到的,它返回上述错误.
However, as I mentioned, it returns the above error.
谁能解释一下我做错了什么
Could someone explain what I am doing wrong
推荐答案
您应该在 .filter(..)
或 .get(..)<中指定参数的名称/code> 调用:
You should specify the name of the parameter in .filter(..)
or .get(..)
calls:
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
是一个内置函数,现在一个局部变量隐藏"了这个内置函数.
I also propose to rename your variable to something else (so both in the urls.py
and views.py
), since id
is a builtin function, and now a local variable is "hiding" this builtin.
这篇关于类型错误:无法在 Django 视图函数中解压不可迭代的 int 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!