24. 결과(result) 조회 페이지

data_hamster·2023년 4월 26일

학습주제
결과(result) 조회 페이지

학습내용
투표한 결과를 조회하는 화면 생성.

view.py로 이동.
request, question에 대한 결과이므로 question_id를 받는다.

def result(request, question_id):
	question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/result.html', {'question':question})

urly.py로 이동
detail을 재활용
path('<int:question_id>/result', views.result, name='result')

template으로 이동 result.html 생성 후, 코드 재활용

  • form은 필요 없으니 제거.
  • csrf_token 제거
  • 에러메세지 제거
  • input type=radio 제거
  • label for 제거
<h1>{{question.question_text}}</h1><br>
{% for choice in question.choice_set.all %}
	<label>
      {{choice.choice_text}} -- {{choice.votes}}
	</label>
	<br>
{% endfor %}

투표를 한 후에, 이 result 페이지를 보여주도록 한다.

views.py로 이동
vote 메소드에서 return 을 reverse('polls:result') 로 바꿈
return HttpResponseRedirect(reverse('polls:result'))
그러나 result는 아무것도 주어지지 않았을 때 만들 수 있는 url이 아님
어떤 question에 대한 result인지 알아야 함. index의 경우 아무것도 주어지지 않아도 바로 만들 수 있음. 전달하는 방법은 뒤에 , args = (question_id,) 인데, 이때 컴마(,)를 빼지 않도록 주의한다. 여러개의 args가 들어갈 수 있는데 그 중 question_id가 들어간다는 뜻.

return HttpResponseRedirect(reverse('polls:result', args = (question_id,)))

개발자도구 - 네트워크 - 이름 vote/ - 헤더를 보면

302는 302 리다이렉트라고도 함. 우리가 vote에서 return으로 HttpResponseRedirect를 사용했기 때문.

기억하기

return HttpResponseRedirect(reverse('polls:result', args = (question_id,)))
리다이렉트를 할 때, 새로운 값을 전달하는 방법.

profile
반갑습니다 햄스터 좋아합니다

0개의 댓글