首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,Django,教程,测试详细信息视图,错误

Python,Django,教程,测试详细信息视图,错误
EN

Stack Overflow用户
提问于 2016-03-03 17:02:51
回答 2查看 972关注 0票数 0

我正在阅读Django教程,并且在教程5>“测试详细视图”中遇到了错误。

当我运行时:

python manage.py test polls

在终端中,我收到了这样的消息:

代码语言:javascript
复制
Creating test database for alias 'default'...
.F.......
======================================================================
FAIL: test_detail_view_with_a_past_question (polls.tests.QuestionIndexDetailTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/theoford/Documents/python/04_django_intro/mysite/polls/tests.py", line 115, in test_detail_view_with_a_past_question
    status_code=200)
  File "/Library/Python/2.7/site-packages/django/test/testcases.py", line 398, in assertContains
    msg_prefix + "Couldn't find %s in response" % text_repr)
AssertionError: Couldn't find 'Past Question.' in response

----------------------------------------------------------------------
Ran 9 tests in 0.030s

FAILED (failures=1)
Destroying test database for alias 'default'...

这是我在tests.py中拥有的与“使用过去的问题测试详细视图”相关的代码(这是后面的函数)。

代码语言:javascript
复制
class QuestionIndexDetailTests(TestCase):
    def test_detail_view_with_a_future_question(self):
        """
        The detail view of a question with a pub_date in the future should
        return a 404 not found.
        """
        future_question = create_question(question_text='Future question.',
                                          days=5)
        response = self.client.get(reverse('polls:detail',
                                   args=(future_question.id,)))
        self.assertEqual(response.status_code, 404)

    def test_detail_view_with_a_past_question(self):
        """
        The detail view of a question with a pub_date in the past should
        display the question's text.
        """
        past_question = create_question(question_text='Past Question.',
                                        days=-5)
        response = self.client.get(reverse('polls:detail',
                                   args=(past_question.id,)))
        self.assertContains(response, past_question.question_text,
                            status_code=200)

我是Stackoverflow社区的新手,所以如果这个问题的格式不正确、不完整或不合适,我深表歉意,但任何对解决此问题的帮助都将不胜感激。

views.py:

代码语言:javascript
复制
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 django.utils import timezone 

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 (not including those published in the future)."""
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

class DetailView(generic.DetailView):
    model = Question 
    template_name = 'polls/detail.html'

    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

class ResultsView(generic.DetailView):
    model = Question 
    template_name = 'polls/results.html'

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
EN

回答 2

Stack Overflow用户

发布于 2016-03-09 02:36:43

你想检查一下那个“过去的问题”吗?是在response.content中,而不是response中。将test_detail_view_with_a_past_question的最后一行更改为:

代码语言:javascript
复制
self.assertContains(response.content, past_question.question_text,
                        status_code=200)
票数 0
EN

Stack Overflow用户

发布于 2021-01-07 06:48:08

在我的案例中,测试用例以两种方式通过:

通过将属性pk_url_kwargs添加到views.py中具有值'question_id‘的DetailView来执行

pk_url_kwargs = 'question_id'

通过将urls.py中的'question_id‘更改为'pk’来

path('/',views.DetailView.as_view(),name='detail'),

原因:

据我所知,泛型DetailView默认根据名为'pk‘或'slug’的参数查找对象-- (选取一个主键等于名为‘pk’的变量的值的对象),但在urls.py教程中,额外的整数参数被命名为'question_id‘,因此我们需要更改views.py中的pk_url_kwargs或urls.py中的参数名称。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35767497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档