AssertionError: Шаблон не был шаблоном, используемым для отображения ответа
Я столкнулся с проблемой в TestCase, когда он утверждает, что фактический шаблон, используемый для отображения ответа, не соответствует шаблону, который я ожидаю. Возникает следующая ошибка:
AssertionError: False is not true : Template 'posts/question.html' was not a template used to render the response. Actual template(s) used: posts/ask.html, ..., ...
Все, что после posts/ask.html, относится к встроенным шаблонам.
Последовательность событий:
- Нажмите "Задать вопрос" -> опубликуйте форму вопроса -> перенаправление на страницу вопроса -> нажмите редактировать -> опубликуйте редактирование вопроса -> перенаправление на страницу вопроса .
Я не могу определить, где или почему Django говорит, что отображается posts/ask.html. Насколько я могу судить, я перенаправляю на правильный URL, где он должен отобразить posts/question.html.
class TestPostEditQuestionPage(TestCase):
'''Verify that a message is displayed to the user in the event
that some aspect of the previous posted question was edited.'''
@classmethod
def setUpTestData(cls):
cls.user = get_user_model().objects.create_user(
username="OneAndOnly",
password="passcoderule"
)
profile = Profile.objects.create(user=cls.user)
tag = Tag.objects.create(name="TagZ")
question = Question.objects.create(
title="This is Question Infinity",
body="The is the content body for This is Question Infinity",
profile=profile
)
question.tags.add(tag)
cls.data = {
"title": "This is Question Zero",
"body": "The is the content body for This is Question Infinity",
"tags": ["TagZ", "TagA"]
}
def test_posted_question_content_changed(self):
self.client.force_login(self.user)
response = self.client.post(
reverse("posts:edit", kwargs={"id": 1}),
data=self.data, follow=True
)
print([template.name for template in response.templates])
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "posts/question.html")
self.assertContains(response, "Question updated!")
class AskQuestionPage(Page):
template_name = "posts/ask.html"
extra_context = {
'title': "Ask a public question"
}
def attach_question_tags(self, tags):
question_tags = []
for name in tags:
try:
tag = Tag.objects.get(name=name)
except Tag.DoesNotExist:
tag = Tag.objects.create(name=name)
finally:
question_tags.append(tag)
return question_tags
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = QuestionForm
return context
def post(self, request):
context = self.get_context_data()
form = context['form'](request.POST)
if form.is_valid():
tags = self.attach_question_tags(form.cleaned_data.pop("tags"))
question = form.save(commit=False)
question.profile = request.user.profile
question.save()
question.tags.add(*tags)
form.save_m2m()
return SeeOtherHTTPRedirect(
reverse("posts:question", kwargs={"id": question.id})
)
return self.render_to_response(context)
class EditQuestionPage(AskQuestionPage):
extra_context = {
'title': "Edit your question"
}
def get(self, request, id):
question = get_object_or_404(Question, id=id)
context = self.get_context_data()
context['form'] = context['form'](instance=question)
return self.render_to_response(
context, headers={
'Content-Type': "text/html"
}
)
def post(self, request, id):
question = get_object_or_404(Question, id=id)
context = self.get_context_data()
form = context['form'](request.POST, instance=question)
if form.is_valid():
if form.has_changed():
messages.success(request, "Question updated!")
x = form.cleaned_data.pop("tags")
tags = self.attach_question_tags(x)
question = form.save()
question.tags.set(tags)
return SeeOtherHTTPRedirect(reverse(
"posts:question", kwargs={"id": id}
))
return self.render_to_response(context)
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, id):
context = self.get_context_data()
question = get_object_or_404(Question, id=id)
context['question'] = question
return self.render_to_response(context)
posts_patterns = ([
path("", pv.QuestionListingPage.as_view(), name="main"),
path("questions/ask/", pv.AskQuestionPage.as_view(), name="ask"),
path("questions/edit/<id>/", pv.EditQuestionPage.as_view(), name="edit"),
path("questions/<id>/", pv.PostedQuestionPage.as_view(), name="question")
], "posts")