表单提交在Django教程中保持失败

时间:2012-11-01 17:00:15

标签: python django

我在Django tutorial (part 4)并试图创建一个表单,允许用户选择回答民意调查。问题加载正确,但是当我点击“投票”(即选择选项和提交表单)时,以下错误会一直显示:

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.

以下是来自detail.html的代码,其格式为:

{{ 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>

我怀疑问题出在<form action="/polls/vote/{{ poll.id }} " method="post">行,但我不确定如何解决。

3 个答案:

答案 0 :(得分:6)

您的投票ID和vote操作已被撤消。

您的网址格式为:

^polls/ ^(?P<poll_id>\d+)/vote/$ [name='vote']

但您的表单操作指向vote/id。反转那些:

<form action="/polls/{{ poll.id }}/vote" method="post">

请注意,本教程实际上使用不同的方法来生成该URL;它使用:

<form action="{% url 'polls:vote' poll.id %}" method="post">

其中url filter为您生成正确的URL,给定polls:vote路由配置和当前投票对象的ID(poll.id)。

使用{% url routename arguments %}可让您以后更轻松地更改路线,而无需更正所有模板。

答案 1 :(得分:4)

将网址更改为/ polls / {{poll.id}} / vote /

答案 2 :(得分:0)

在之前的 tut03 中,他们删除了 url 的硬编码部分 现在是<form action="{% url 'polls:vote' question.id %}" method="post">

这应该有效