AssertRedirects(response) вызывает ошибку NoReverseMatch;

Я тестирую сценарий, в котором пользователь успешно редактирует ответ в ответ на вопрос. После редактирования ответа пользователь перенаправляется на страницу листинга с вопросом и всеми размещенными ответами.

Проблема заключается в том, что пользователь не перенаправляется; возникает ошибка NoReverseMatch:

  • Reverse for 'question' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['questions/(?P<question_id>[^/]+)/$']

self.assertRedirects() вызывает эту ошибку в тесте. Однако я не могу определить, почему она возникает, когда question_id передается в reverse("posts:question", kwargs={"question_id": answer.question.id}) вызов assertRedirects()? Он говорит, что ключом является 'id'?

class TestEditInstanceAnswerPage(TestCase):
    '''Verify that a User who has posted an Answer to a given Question
    has the ability to edit their answer.'''

    @classmethod
    def setUpTestData(cls):
        cls.user = get_user_model().objects.create_user("TestUser")
        cls.profile = Profile.objects.create(user=cls.user)
        cls.answer_user = get_user_model().objects.create_user("TheAnswer")
        cls.answer_profile = Profile.objects.create(user=cls.answer_user)
        cls.tag = Tag.objects.create(name="Tag1")
        cls.question = Question.objects.create(
            title="How do I get an answer to my post",
            body="This is the content that elaborates on the title that the user provided",
            profile=cls.profile
        )
        cls.question.tags.add(cls.tag)
        cls.answer = Answer.objects.create(
            body="This is an answer in response to 'How do I get an answer to my post'",
            question=cls.question,
            profile=cls.answer_profile
        )
        cls.data = {
            "body": "This is a not a very good question. Let me explain why."
        }

    def test_post_request_edited_answer(self):
        self.client.force_login(self.answer_user)
        response = self.client.post(
            reverse("posts:answer_edit", kwargs={
                "question_id": self.question.id,
                "answer_id": self.answer.id
            }), data=self.data
        )
        self.assertRedirects(
            response, reverse("posts:question", kwargs={'question_id': 1}),
            status_code=303
        )
class PostedQuestionPage(Page):

    template_name = "posts/question.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['answer_form'] = AnswerForm
        return context

    def get(self, request, question_id):
        context = self.get_context_data()
        question = get_object_or_404(Question, id=question_id)
        context['question'] = question
        return self.render_to_response(context)


class EditPostedAnswerPage(PostedQuestionPage):

    def get(self, request, question_id, answer_id):
        context = super().get_context_data()
        question = get_object_or_404(Question, id=question_id)
        answer = get_object_or_404(Answer, id=answer_id)
        context.update({
            "answer_form": context['answer_form'](instance=answer),
            'question': question,
            'answer': answer
        })
        return self.render_to_response(context)

    def post(self, request, question_id, answer_id):
        context = super().get_context_data()
        question = get_object_or_404(Question, id=question_id)
        answer = get_object_or_404(Answer, id=answer_id)
        if context['answer_form'](request.POST, instance=answer).is_valid():
            return SeeOtherHTTPRedirect(
                reverse("posts:question", kwargs={
                    'question_id': answer.question.id
                })
            )

posts_patterns = ([
    path("", pv.QuestionListingPage.as_view(), name="main"),
    path("questions/ask/", pv.AskQuestionPage.as_view(), name="ask"),
    path("questions/<question_id>/edit/", pv.EditQuestionPage.as_view(), name="edit"),
    path("questions/<question_id>/edit/answers/<answer_id>/", pv.EditPostedAnswerPage.as_view(), name="answer_edit"),
    path("questions/<question_id>/", pv.PostedQuestionPage.as_view(), name="question")
], "posts")
Вернуться на верх