Python 页面未正确重定向

Python 页面未正确重定向,python,django,Python,Django,我正在自学django,当我今天学习教程时,遇到了这个问题。我使用django 1.9.7和Python3.5.2 64位和PyCharm 当我选择一个选项并单击“投票”按钮时,它会被重定向到结果页面,但我会收到错误消息:您没有选择一个选项,而当我一直没有选择任何选项时,您可能会选择该选项。我检查了我的代码,我想一定是函数投票出了问题,但我不知道原因 轮询\view.py def vote(request, question_id): question = get_object_or_4

我正在自学django,当我今天学习教程时,遇到了这个问题。我使用django 1.9.7和Python3.5.2 64位和PyCharm

当我选择一个选项并单击“投票”按钮时,它会被重定向到结果页面,但我会收到错误消息:您没有选择一个选项,而当我一直没有选择任何选项时,您可能会选择该选项。我检查了我的代码,我想一定是函数投票出了问题,但我不知道原因

轮询\view.py

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except(KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results',args=(question.id,)))
轮询\url.py

from django.conf.urls import url
from . import views

app_name = 'polls'
urlpatterns = [
    url(r'^$', views.index, name = 'index'),
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
轮询\template\polls\detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" methon="post">
{% csrf_token %}
{% for choice in question.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>
</body>
</html>

对不起,浪费了你所有的时间。是打字错误造成了这个问题。 轮询\template\polls\detail.html
方法应该是方法,问题已经解决了。

对不起,浪费了你所有的时间。是打字错误造成了这个问题。 轮询\template\polls\detail.html
methon应该是method,问题已经解决。

为什么不使用表单分析发布的数据?删除try/except,看看Django遇到了什么实际错误。@Daniel Roseman如果没有语法错误Remove try,except and else,我无法删除try或except,并另外删除except块中的代码,只保留try中的代码。必须在view函数中执行。为什么不使用form来分析发布的数据?删除try/except,看看Django遇到了什么实际错误。@Daniel Roseman如果没有语法错误Remove try,except and else,我无法删除try或except,另外,删除except块中的代码,只保留try块中的代码。您必须在view函数中执行此操作。