ListView for Django not working但基于功能的视图正在运行

时间:2017-07-31 17:38:51

标签: django django-views

当我使用以下代码使用基于功能的视图时:

来自django.views导入视图 来自django.views.generic导入TemplateView,ListView

from .models import Restaurant
def restaurant_listview(request):
    template = 'restaurants/restaurants_list.html'
    context = {
    "queryset" : Restaurant.objects.order_by('-updated')
    }
    return render (request, template, context)

它正在使用url文件,如下所示:

from django.conf.urls import url
from django.contrib import admin
from restaurants import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^restaurants/$', views.restaurant_listview),
]

但是当我尝试使用基于类的视图做同样的事情时,它不起作用,只有以下部分似乎不起作用:

<ul>
  {% for obj in queryset %}
  <li>{{obj.name}}, {{obj.location}}, {{obj.category}}, {{obj.timestamp}}</li>
  {% endfor %}
</ul>

以下部分正常工作:

{% extends 'base.html' %}
{% block title %}
Restaurants List {{ block.super }}
{% endblock %}
{% block content %}
<h1>Restaurants</h1>

基于类的视图我的views.py是:

class RestaurantListView(ListView):
    queryset = Restaurant.objects.all()
    template_name = 'restaurants/restaurants_list.html'

和urls.py是:

url(r'^restaurants$', RestaurantListView.as_view(), name='Home')

P.S。我正在遵循本指南:https://www.youtube.com/watch?v=yDv5FIAeyoY&t=25471s

1 个答案:

答案 0 :(得分:1)

对于列表视图,您应该将模板更改为:

{% for obj in restaurant_list %}

或者,如果您确实想在模板中使用变量queryset,请设置context_object_name

class RestaurantListView(ListView):
     queryset = Restaurant.objects.all()
     template_name = 'restaurants/restaurants_list.html'
     context_object_name = 'queryset'