【发布时间】:2015-06-06 05:46:38
【问题描述】:
我正在学习https://docs.djangoproject.com/en/1.7/intro/tutorial04/ 中的 Django 1.7 教程。 我从网上复制代码,然后运行它。我遇到两个问题:
- 添加继承ListView的IndexView后,127.0.0.1:8000/polls页面只返回“No polls are available”。没有任何数据库项目。我对基于分类的视图感到困惑,似乎上下文值没有传递给模板。 ---------> 解决了,这是我的愚蠢类型错误。
- get_queryset(),是干什么用的,当这个方法被调用时,这个是如何映射到上下文的?这个函数怎么知道上下文映射,如果有两个上下文和两个值呢?
有人可以在这里给我一些指导吗?非常感谢。
投票/urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
#url(r'^$', views.index, name='index'), #this url works
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
)
polls/views.py
from django.http import HttpResponse, Http404,HttpResponseRedirect
from django.template import RequestContext, loader
from django.shortcuts import render,get_object_or_404
from .models import Question, Choice
from django.core.urlresolvers import reverse
from django.views import generic
class IndexView(generic.ListView):
template_name ='polls/index.html'
context_object_name = 'last_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
#this works
#def index(request):
# latest_question_list = Question.objects.order_by('-pub_date')[:5]
# context = {'latest_question_list': latest_question_list}
# return render(request, 'polls/index.html', context)
民意调查/index.html
{% if latest_question_list %} <!-- seems here value is not passed by -->
<ul>
{% for question in latest_question_list %}
<li>
{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>{{ latest_question_list }}</p>
<p>No polls are available.</p> <!-- always display this -->
<p>{{ latest_question_list }}</p>
{% endif %}
数据库
>>> from polls.models import Question
>>> Question.objects.all()
[<Question: What's up?>, <Question: tttt>]
【问题讨论】:
-
请注意,
context_object_name是 'last_question_list',但在模板中您正在检查 'latest_question_list' -
是的,解决了。真是愚蠢的错误。但是 last_question_list 仍然是如何映射到上下文的?我猜是通过 get_queryset(),但是 Question.objects.order_by('-pub_date')[:5] 是如何自动链接到 last_question_list 的。