[Django]-Official Django Tutorial, Test Client, Contexts

3👍

Welcome !

The problem with your question is that you don’t show us how to get the same response object as you do on our own, therefore, we can’t reproduce your problem.

The problem with your context object is that it’s None, request.context is None in your case so that’s why ‘[…]’ – which calls __getitem__ – fails hence the exception “NoneType has no attribute __getitem__“.

For me django test client’s response has a context all right:

$ ./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'...

To get this debugger inside my test, this is the code i added to polls/test.py:

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

Don’t forget to pip install ipdb, or use pdb here instead of ipdb.

Also, please consider reading PEP8 and PEP0257, if you haven’t already, but perhaps you’ve read it after starting polls/tests.py.

👤jpic

3👍

The problem described by the OP will also occur if you use Jinja2 templates instead of DTL.
So if you have followed along in the tutorial but have amended settings.py to use jinja2, you will have the following lines in a python shell:

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

As you can see, response.context is None because Jinja2 has not filled it. Instead use context_data when using Jinja2:

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

Leave a comment