diff --git a/polls/tests.py b/polls/tests.py index 7192b14..6274ef9 100644 --- a/polls/tests.py +++ b/polls/tests.py @@ -34,8 +34,8 @@ class QuestionModelTests(TestCase): time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) - - + + def create_question(question_text, days): """ Create a question with the given `question_text` and published the @@ -43,10 +43,10 @@ def create_question(question_text, days): in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) - - + return Question.objects.create(question_text=question_text, pub_date=time) + class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ @@ -102,4 +102,26 @@ class QuestionIndexViewTests(TestCase): self.assertQuerySetEqual( response.context["latest_question_list"], [question2, question1], - ) \ No newline at end of file + ) + + +class QuestionDetailViewTests(TestCase): + def test_future_question(self): + """ + The detail view of a question with a pub_date in the future + returns a 404 not found. + """ + future_question = create_question(question_text="Future question.", days=5) + url = reverse("polls:detail", args=(future_question.id,)) # type: ignore + response = self.client.get(url) + self.assertEqual(response.status_code, 404) + + def test_past_question(self): + """ + The detail view of a question with a pub_date in the past + displays the question's text. + """ + past_question = create_question(question_text="Past Question.", days=-5) + url = reverse("polls:detail", args=(past_question.id,)) # type: ignore + response = self.client.get(url) + self.assertContains(response, past_question.question_text) diff --git a/polls/views.py b/polls/views.py index 9150aed..a039ae5 100644 --- a/polls/views.py +++ b/polls/views.py @@ -19,15 +19,21 @@ class IndexView(generic.ListView): Return the last five published questions (not including those set to be published in the future). """ - return Question.objects.filter(pub_date__lte=timezone.now()).order_by("-pub_date")[ - :5 - ] + 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