【问题标题】:django pass response context nonedjango传递响应上下文无
【发布时间】:2014-03-21 15:13:41
【问题描述】:

在我的浏览器中,一切正常。直到我做一个测试

这是我的投票/views.py

from django.shortcuts import render
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')
    context = {'latest_poll_list':latest_poll_list}
    return render(request,'polls/index.html',context)

投票/模板/投票/index.html

{% if latest_poll_list %}
    <ul>
    {% for poll in latest_poll_list %}
        <li>{{poll.question}}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No Poll Available</p>
{% endif %}

还有我的 polls/tests.py

from django.test import TestCase
from django.core.urlresolvers import reverse

class SimpleTest(TestCase):
    def test_this(self):
        response = self.client.get(reverse('polls.views.index'))
        print response.context
        print response.content

如您所见,我的response.context['latest_poll_list'] 始终是[]

所以我想知道我的错在哪里?

【问题讨论】:

    标签: python django django-testing django-tests


    【解决方案1】:

    如果在浏览器中你得到你的对象,这意味着你的视图是好的,如果你的测试没有返回任何对象,你可能必须创建它们(测试使用 Django 从头开始​​自动创建的空数据库)。我通常在 setUp() 方法中创建示例对象:

    class SimpleTest(TestCase):
    
        def setUp(self):
            self.poll = Poll.objects.create()
    

    【讨论】:

    • 好吧,从技术上讲,它是有效的。但是我想知道,如果我有很多表,我是否必须像这样一张一张地创建它们?谢谢
    • 您可以使用固定装置,但通常您不会针对数千条记录进行测试,因此为每个测试创建几条记录是完全正常的……您正在编写 UNIT 测试,即:您的应用程序中最简单和最少量的代码,您不必处理整个数据集:)
    猜你喜欢
    • 1970-01-01
    • 2011-05-07
    • 2015-01-24
    • 2022-11-19
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多