강의로 돌아가기
url 방식이 잘못되어 표시가 되지 않습니다.
현재
http://localhost:8000/elections/areas/미국/elections/polls/1/
이런식으로 보입니다.
제가 의도한 url은
http://localhost:8000/elections/polls/1/
입니다.
urls.py는
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^areas/(?P<area>.+)/$', views.areas),
url(r'^polls/(?P<poll_id>\d+)/$', views.polls),
]
이며
views.py는
def polls(request, poll_id):
poll = Poll.objects.get(pk=poll_id)
selection = request.POST['choice']
try:
choice = Choice.objects.get(poll_id=poll_id, candidate_id=selection)
choice.votes += 1
choice.save()
except:
choice = Choice(poll_id=poll_id, candidate_id=selection, votes=1)
choice.save()
return HttpResponse("finish")
입니다.
추가적으로
project urls.py는
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^elections/', include('elections.urls')),
]
html 부분은
<td>
<form action = "elections/polls/{{poll.id}}/" method="post">
{% csrf_token %}
<button name="choice" value="{{candidate.id}}">선택</button>
</form>
이상입니다.
덧. 마크다운이 좀 이상하게 적용 되는 것 같습니다.(스택에디트에서는 제대로 코드 나오는 것을 확인 했습니다)
1 개의 답변
html에 <form action = "elections/polls/{{poll.id}}/" method="post">
를 수정해주셔야 합니다.
시작 부분에 /
가 있어야 root path로 인식됩니다. 이렇게 /
를 추가해주세요
<form action = "/elections/polls/{{poll.id}}/" method="post">