【问题标题】:Class based view won't work while function based view works(Django)基于类的视图不起作用,而基于函数的视图起作用(Django)
【发布时间】:2020-12-25 00:30:13
【问题描述】:

当我尝试创建基于函数的视图时,它会起作用,显示我的查询集。这是我在下面使用的代码。 在views.py中

def restaurant_listview(request):
template_name ="restaurant/restaurantlist.html"
query_set = Restaurant.objects.all() #all the objects that are stored in da DB
context={"list": query_set}
return render(request,template_name, context)

但是当我尝试将其作为基于类的视图时,它不会显示我的查询集。

在views.py中

`class RestaurantListView(ListView):
queryset = Restaurant.objects.all()
template_name ="restaurant/restaurantlist.html"`

在 urls.py 中

path('restaurants', RestaurantListView.as_view()

我该如何解决这个问题?

【问题讨论】:

    标签: python django listview


    【解决方案1】:

    我认为您应该更改 RestaurantListView 中的上下文配置,例如:

    class RestaurantListView(ListView):
        queryset = Restaurant.objects.all()
        template_name ="restaurant/restaurantlist.html"`
        context_object_name = 'list'
    

    因为您似乎在模板代码中使用了旧的上下文名称。

    【讨论】:

      猜你喜欢
      • 2013-04-06
      • 1970-01-01
      • 2019-09-24
      • 2021-07-12
      • 2012-10-23
      • 2014-02-16
      • 1970-01-01
      • 2023-03-19
      • 2023-03-14
      相关资源
      最近更新 更多