ValueError: Поле 'id' ожидало число, но получило '<built-in function id>'; Перенаправление POST-запроса
Когда пользователь успешно выполняет POST
запрос на редактирование собственного вопроса, он перенаправляется на страницу подробностей того же вопроса. При последующем запросе GET
к представлению PostedQuestionPage
после редактирования вопроса возникает следующая ошибка ValueError при попытке получить экземпляр с get_object_or_404()
:
ValueError: Field 'id' expected a number but got '<built-in function id>'
Почему передается PostedQuestionPage
, а не значение, которое должно представлять идентификатор экземпляра вопроса? '<built-in function id>'
> c:\..\posts\views.py(137)get()
-> question = get_object_or_404(Question, id=question_id)
(Pdb) ll
134 def get(self, request, question_id):
135 import pdb; pdb.set_trace()
136 context = self.get_context_data()
137 -> question = get_object_or_404(Question, id=question_id)
138 context['question'] = question
139 return self.render_to_response(context)
(Pdb) question_id
'<built-in function id>'
(Pdb) n
ValueError: Field 'id' expected a number but got '<built-in function id>'.
> c:\..\posts\views.py(137)get()
-> question = get_object_or_404(Question, id=question_id)
(Pdb) n
--Return--
> c:\..\posts\views.py(137)get()->None
-> question = get_object_or_404(Question, id=question_id)
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_0": "TagN", "tags_1": "TagZ"
}
def test_posted_question_content_changed(self):
self.client.force_login(self.user)
response = self.client.post(
reverse("posts:edit", kwargs={"question_id": 1}),
data=self.data
)
self.assertRedirects(
response, reverse("posts:question", kwargs={"question_id": 1}),
status_code=303
)
class Page(TemplateView):
def get_context_data(self, **kwargs):
context = super().get_context_data()
context['search_form'] = SearchForm()
return 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, 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)
def post(self, request, question_id):
question = get_object_or_404(Question, id=question_id)
context = super.get_context_data()
form = context['answer_form'](request.POST)
if form.is_valid():
form.cleaned_data.update({"profile": request.user.profile})
answer = Answer.objects.create(
**form.cleaned_data, question=question
)
return SeeOtherHTTPRedirect(
reverse("posts:question", kwargs={
"question_id": answer.question.id
})
)
class EditQuestionPage(AskQuestionPage):
...
def post(self, request, question_id):
...
return SeeOtherHTTPRedirect(reverse(
"posts:question", kwargs={"question_id": id}
))
В этом и заключается проблема. Вы передаете встроенную функцию id
как question_id
.