所以我开始学习本教程的通用 View 部分,直到此时一切都很顺利,工作完美,然后我收到此错误: 未找到参数“(”,)”和关键字参数“{}”的“投票”的反向操作。尝试了 1 个模式:[u'polls/(?P[0-9]+)/vote/$']
这是我的 urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name ='vote'),
]
这是我的观点.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.http import Http404
from .models import Choice, Quesion
from django.core.urlresolvers import reverse
from django.views import generic
# Create your views here.
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Quesion.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Quesion
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Quesion
template_name = 'polls/results.html'
def vote(request, question_id):
p = get_object_or_404(Quesion, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': p,
'error_message':"No choice selected",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results',args=(p.id,)))
这是我的detail.html
<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 question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_txt }} </label><br />
{% endfor %}
<input type="submit" value="vote" />
</form>
最佳答案
你有两个问题。第一个是 DetailView
在模板中没有提供 question
变量,而是提供了一个名为 object
的变量。因此模板中所有 question
实例都需要更改为 object
。
其次,URL 需要关键字参数 question_id
,但您将非关键字参数传递给 {% url %}
标记。您需要将其更改为 question_id=object.id
。您的 detail.html
应如下所示:
<h1>{{ object.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question_id=object.id %}" method="post">
{% csrf_token %}
{% for choice in object.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_txt }} </label><br />
{% endfor %}
<input type="submit" value="vote" />
</form>
关于python - NoReverseMatch Django 教程 1.8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29558154/