页面无法正确重定向

时间:2016-07-12 08:16:15

标签: python django

我正在和自己一起学习django,当我今天关注教程Writing your first Django app, part 4时,我遇到了这个问题。(我正在使用django 1.9.7和Python 3.5.2 64位和PyCharm)< / p>

当我选择一个选项并单击按钮投票时,它假设被重定向到结果页面,但是我收到错误消息:“你没有选择一个选择”,当我不这样做时一直选择任何选择。我检查了我的代码,我认为函数投票肯定出错,但我不知道原因。

轮询\ 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,)))

轮询\ urls.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'),
]

轮询\模板\轮询\ 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>

1 个答案:

答案 0 :(得分:0)

抱歉浪费你所有的时间。这是一个错字导致了这个问题。

轮询\模板\轮询\ detail.html <form action="{% url 'polls:vote' question.id %}" methon="post">

methon应为method,问题已解决。