我在學習如下Django 1.7教程https://docs.djangoproject.com/en/1.7/intro/tutorial04/。 我從網上覆制代碼,然後運行它。我遇到兩個問題:上下文值似乎沒有傳遞到Django中的ListView?
- 在添加繼承ListView的IndexView後,127.0.0.1:8000/polls頁面剛剛返回「沒有民意調查可用」。沒有任何數據庫項目。我對基於分類的觀點感到困惑,似乎上下文值並沒有傳遞給模板。 ---------->解決,這是我愚蠢的類型錯誤。
- 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'),
)
民調/ 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'*,但在模板中,您正在檢查*'la ** te ** st_question_list'* – soon
是的,已解決。真是愚蠢的錯誤。但仍然如何將last_question_list映射到上下文?我想通過get_queryset(),但問題如何。自動鏈接到last_question_list的objects.order_by(' - pub_date')[:5]。 – Bing