Reputation: 75
I am on the Django tutorial (part 4) and trying to create a form which allows user to choose answer to a poll. The questions load properly, however when I click 'vote' (ie select option and submit form) the following error keeps showing:
Page not found (404)
Request Method: POST
Request URL: http://localhost:8000/polls/vote/6
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/ ^$ [name='index']
^polls/ ^(?P<poll_id>\d+)/$ [name='detail']
^polls/ ^(?P<poll_id>\d+)/results/$ [name='results']
^polls/ ^(?P<poll_id>\d+)/vote/$ [name='vote']
^admin/
The current URL, polls/vote/6, didn't match any of these.
Here is the code from detail.html which has the form:
{{ poll.question }}
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/polls/vote/{{ poll.id }} " method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
I suspect the problem is in the line <form action="/polls/vote/{{ poll.id }} " method="post">
but I'm not sure how to fix it.
Upvotes: 2
Views: 1509
Reputation: 711
in the previous tut03 they have removed the hard-coded part of the url
now it is <form action="{% url 'polls:vote' question.id %}" method="post">
this should work
Upvotes: 0
Reputation: 1122222
You have your poll id and vote
action reversed.
Your url pattern is of the form:
^polls/ ^(?P<poll_id>\d+)/vote/$ [name='vote']
but your form action points to vote/id
instead. Reverse those:
<form action="/polls/{{ poll.id }}/vote" method="post">
Note that the tutorial actually uses a different method to generate that URL; it uses:
<form action="{% url 'polls:vote' poll.id %}" method="post">
where the url
filter generates the correct URL for you, given the polls:vote
route configuration and the id of the current poll object (poll.id
).
Using {% url routename arguments %}
makes it easier for you to later change your routes, without having to then correct all your templates too.
Upvotes: 6