2

我在Django 教程(第 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">,但我不知道如何解决它。

4

3 回答 3

6

您的投票 ID 和vote操作已反转。

您的 url 模式是以下形式:

^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">

在给定路由配置和当前轮询对象 ( )的 id 的情况下,url过滤器会为您生成正确的 URL。polls:votepoll.id

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

于 2012-11-01T17:02:24.350 回答
4

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

于 2012-11-01T17:01:52.560 回答
0

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

这应该工作

于 2021-06-07T08:50:12.867 回答