【问题标题】:Form submission keeps failing in Django Tutorial表单提交在 Django 教程中不断失败
【发布时间】:2012-11-01 17:00:15
【问题描述】:

我在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>

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

【问题讨论】:

    标签: python django


    【解决方案1】:

    您的投票 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 %} 可以让您以后更轻松地更改路线,而不必再更正所有模板。

    【讨论】:

    • 谢谢 Martijn。我曾尝试使用命名空间,但似乎没有用,所以我在 url 中硬编码。
    【解决方案2】:

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

    【讨论】:

    • 是的...这种情况经常发生 :)
    【解决方案3】:

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

    这应该可以工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 2022-10-17
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多