2016-03-01 45 views
3

我正在嘗試做'傳奇'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'] 

我希望這可以回答你的問題。非常感謝您快速回來!再次道歉格式。

+1

response.context是無,您如何獲得響應對象? – jpic

+0

hey jpic?這回答了你的問題了嗎? –

+1

'response.content'顯示什麼?你是否記得設置測試環境,如[教程](https://docs.djangoproject.com/en/1.9/intro/tutorial05/#the-django-test-client)? – Alasdair

回答

3

歡迎!

問題與你的問題是,你沒有告訴我們如何獲得相同的響應對象,因爲我們自己做,因此,我們不能再現您的問題。

你的上下文對象的問題是它沒有,request.context在你的情況下是None,所以這就是爲什麼'[...]'調用__getitem__ - 失敗,因此例外「NoneType沒有屬性__getitem__」。

對我來說,Django的測試客戶端的響應有一個上下文沒事:

$ ./manage.py test polls 
Creating test database for alias 'default'... 
.WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv. 
WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv. 
--Return-- 
None 
> /tmp/04_django_intro/mysite/polls/tests.py(43)test_index() 
    41  def test_index(self): 
    42   response = self.client.get('/') 
---> 43   import ipdb; ipdb.set_trace() 

ipdb> response.context 
[{'False': False, 'None': None, 'True': True}, {'exception': 'Resolver404', 'request_path': u'/'}] 
ipdb> c 
... 
---------------------------------------------------------------------- 
Ran 4 tests in 5.121s 

OK 
Destroying test database for alias 'default'... 

爲了讓我測試這裏面調試,這是我加入到投票代碼/ test.py:

def test_index(self): 
    response = self.client.get('/') 
    import ipdb; ipdb.set_trace() 

不要忘了pip install ipdb,或使用pdb而不是ipdb

此外,請考慮閱讀PEP8PEP0257,如果您還沒有,但也許您在啓動polls/tests.py後已閱讀它。

0

如果您使用Jinja2模板而不是DTL,則OP所描述的問題也會發生。 因此,如果您在本教程中,隨後沿,但已修改settings.py使用的Jinja2,你將有一個python外殼下面幾行:

import django 
django.setup() 
from django.test.utils import setup_test_environment 
setup_test_environment() 
from django.test import Client 
# create an instance of the client for our use 
client = Client() 
# get a response from '/' 
response = client.get('/') 
==> Not Found:/
response.status_code 
==> 404 
from django.urls import reverse 
response = client.get(reverse('polls:index')) 
response.status_code 
==> 200 
response.context['latest_question_list'] 
==> Traceback (most recent call last): 
     Python Shell, prompt 12, line 1 
    builtins.TypeError: 'NoneType' object is not subscriptable 

正如你所看到的,response.context是無因的Jinja2未填寫它。當使用Jinja2時使用context_data

response.context_data['latest_question_list'] 
==> <QuerySet [<Question: What's up?>]>