【发布时间】:2018-05-01 16:32:45
【问题描述】:
我在关注 Django 2.0 教程 Part4 遇到错误:
NoReverseMatch at /polls/1/
Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/vote\\/$']
urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
views.py,我严格按照官方教程一步一步来的:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from .models import Question, Choice
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, "polls/detail.html", {'question':question})
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):
#Redisplay the question voting form
return render(request, 'polls/detail.html', {
'question':question,
'error_message':"You did'nt select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
模板
<h1>{{ question.question_text }}</h1>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'polls:vote' question_id %}" method="post">
{% csrf_token %}
{% for choice in queston.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>
我找不到错误。
【问题讨论】:
-
问题出在您的模板中,您没有显示。
-
ty,我正在重新检查代码并附上模板代码作为答案。 @丹尼尔罗斯曼
-
你为什么把它作为答案?它不是一个。编辑您的问题并将其放在那里。
-
您为什么不直接更新您的问题而不是发布答案?
-
它提醒我“代码太多”,我现在编辑它。@Lemayzeur
标签: django