for ListView的循环没有在Django中迭代数据



不工作的代码

这个代码不起作用,我不知道我的代码出了什么问题。

Views.py

您没有在视图上定义模型名称。添加模型名称并尝试添加自定义context_object_name。为了参考检查此

class BookListView(generic.ListView):
model = Book
context_object_name = 'my_book_list'   # your own name for the list as a template variable
queryset = Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war
template_name = 'books/my_arbitrary_template_name_list.html'  # Specify your own template name/location

您必须指定创建ListView的模型。在您的情况下,将model=Post定义为

from django.views.generic.list import ListView
class PostList(ListView):
model = Post
template_name = 'blog/index.html'
queryset = Post.objects.filter(status=1).order_by("-created_on")

或者您也可以使用get_queryset()作为

from django.views.generic.list import ListView
class PostList(ListView):
# specify the model
model = Post
template_name = 'blog/index.html'
def get_queryset(self, *args, **kwargs):
qs = super(PostList, self).get_queryset(*args, **kwargs)
qs = qs.filter(status=1).order_by("-created_on")
return qs

最新更新