장고를 활용한 웹사이트 만들기 - 7. 투표결과 저장하기
- 투표결과 저장하기
- 먼저 투표 버튼을 눌렀을 때, 투표한 결과를 서버로 전송되도록 해보자.
<form action = "/polls/{{poll.id}}/" method="post"> <!-- action : 선택 결과가 전달될 url --> {% csrf_token %} <button name="choice" value="{{candidate.id}}">선택</button> <!-- value : 전달할 결과 -->
- poll.id를 url, candidate.id를 결과로 전달한다.
- 중간에 있는 {% csrf_token %} 는 토큰이 있는 클라이언트만 서버로 post할 수 있도록 제한해주는 역할을 한다.
url(r'^polls/(?P<poll_id>\d+)/$',views.polls)
- form에서 넘어오는 poll.id는 숫자로 \d+ 조건에 매칭되므로 poll_id라는 그룹명을 갖게된다.
def polls(request, poll_id): poll = Poll.objects.get(pk=poll_id) # Poll 객체를 구분하는 주요 키가 poll_id인 객체를 poll 변수에 할당한다. selection = request.POST['choice'] # 사용자가 선택한 값 (area.html에서 button name) choice = Choice.objects.get(poll_id = poll_id, candidate_id = selection) choice.votes += 1 choice.save() return HttpResponse("finish")
- polls 메서드 추가 후, 투표 버튼을 누르면 이번엔 DoesNotExist 에러가 나는 것을 볼 수 있다.
- 이 에러는 최초 투표 시, 아직 DB에 Choice 객체가 저장되어있지 않아 발생하는 에러다.
- 따라서, 이를 해결하기위해 예외처리를 하여 직접 객체를 생성한다.
def polls(request, poll_id): poll = Poll.objects.get(pk=poll_id) # Poll 객체를 구분하는 주요 키가 poll_id인 객체를 poll 변수에 할당한다. selection = request.POST['choice'] # 사용자가 선택한 값 (area.html에서 button name) try: choice = Choice.objects.get(poll_id = poll_id, candidate_id = selection) choice.votes += 1 choice.save() except: # Choice 객체가 없을 시, 직접 만들어서 저장한다. choice = Choice(poll_id = poll_id, candidate_id = selection, votes = 1) choice.save() return HttpResponse("finish")
- TIP
- Django에서 Foreign Key의 경우 변수명 뒤에 _id를 붙여 사용한다.
웹 개발자가 알려주는 수익형 블로그 고속 성장 A to Z