我正在嘗試做'傳奇'django教程,並遇到了幾個問題。首先,我是Stage 5 - Testing,並通過交互式shell探索Django測試客戶端。我遇到的具體問題是關於請求:官方Django教程,測試客戶端,上下文
>>> response.context['latest_question_list']
我得到的迴應是
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'NoneType' object has no attribute '__getitem__'
一切工作正常,直到這個階段,但已經忽略了這個問題,並試圖繼續,我認爲這可能是導致進一步錯誤的原因。
我對Python和Django都很新,從我迄今爲止的挖掘中已經確定,在這種情況下['latest_question_list']的上下文表現爲一個字典,其中附有問題,因此我的問題是爲什麼這本字典中沒有內容?
這是從我views.py代碼,我認爲這是負責該功能:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
我道歉,如果這個問題寫成不好,因爲這是我的第一次。此外,對於那些更好奇或需要我的代碼的進一步信息的任何人,請按照鏈接到這個混帳,其中包含一個最新的例子 - Github.
非常感謝任何人誰耐心,以幫助我解決這個問題。
------------- >> Ammendment
從JPIC答案建立在,希望這個解釋我是如何得到的迴應對象:
>>> from django.test import Client
>>> # create an instance of the client for our use
>>> client = Client()
>>> # get a response from '/'
>>> response = client.get('/')
>>> from django.core.urlresolvers import reverse
>>> response = client.get(reverse('polls:index'))
>>> from polls.models import Question
>>> from django.utils import timezone
>>> response = client.get('/polls/')
>>> response.content
>>> response.context['latest_question_list']
我希望這可以回答你的問題。非常感謝您快速回來!再次道歉格式。
response.context是無,您如何獲得響應對象? – jpic
hey jpic?這回答了你的問題了嗎? –
'response.content'顯示什麼?你是否記得設置測試環境,如[教程](https://docs.djangoproject.com/en/1.9/intro/tutorial05/#the-django-test-client)? – Alasdair