通用视图没有 return 任何值
generic view does not return any values
我是django的初学者,它的版本是1.11.6
,我使用的python版本是3.6
。
我正在研究通用视图,generic.ListView
没有return任何值。
views.py
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'Latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
urls.py
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultView.as_view(), name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote, name='vote'),
]
以上代码的输出是:
no polls are available
html页面包含以下代码:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>no polls are available</p>
{% endif %}
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"/>
很遗憾,我无法得到错误的原因。
问题是您的视图中有 context_object_name = 'Latest_question_list'
(大写 L),它与模板中的 {% if latest_question_list %}
(全部小写)不匹配。
更改视图或模板以使其匹配。 PEP 8 风格指南会推荐 latest_question_list
,所以我会更改视图:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
我是django的初学者,它的版本是1.11.6
,我使用的python版本是3.6
。
我正在研究通用视图,generic.ListView
没有return任何值。
views.py
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'Latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
urls.py
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultView.as_view(), name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote, name='vote'),
]
以上代码的输出是:
no polls are available
html页面包含以下代码:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>no polls are available</p>
{% endif %}
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"/>
很遗憾,我无法得到错误的原因。
问题是您的视图中有 context_object_name = 'Latest_question_list'
(大写 L),它与模板中的 {% if latest_question_list %}
(全部小写)不匹配。
更改视图或模板以使其匹配。 PEP 8 风格指南会推荐 latest_question_list
,所以我会更改视图:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'