Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: cannot unpack non-iterable int object in Django views function

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'),

]

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

like image 535
jeff Avatar asked Nov 10 '18 19:11

jeff


1 Answers

You should specify the name of the parameter in .filter(…) [Django-doc] or .get(…) [Django-doc] 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)

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.

like image 132
Willem Van Onsem Avatar answered Oct 17 '22 19:10

Willem Van Onsem