我在做DjangoCMS教程:http://django-cms.readthedocs.org/en/latest/introduction/plugins.html
在此之前一切都很好,但是当我尝试将Poll插件添加到某个占位符时出现以下错误:
Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['en/polls/(?P<poll_id>\\d+)/vote/$']
模板:
<h1>{{ instance.poll.question }}</h1>
<form action="{% url 'polls:vote' instance.poll.id %}" method="post">
{% csrf_token %}
<div class="form-group">
{% for choice in instance.poll.choice_set.all %}
<div class="radio">
<label>
<input type="radio" name="choice" value="{{ choice.id }}">
{{ choice.choice_text }}
</label>
</div>
{% endfor %}
</div>
<input type="submit" value="Vote" />
观点:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
return Poll.objects.all()[:5]
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.html'
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render(request, 'polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
错误发生在第<form action="{% url 'polls:vote' 'instance.poll.id' %}" method="post">
行
投票应用的urls.py:
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),)
迁移正常,Poll插件显示在插件列表中,甚至弹出选择插件对象打开不错。当我添加插件并确认时,网页崩溃了。要让网站再次打开,我需要手动删除/ admin上的页面。
我也尝试将instance.poll.id放在单引号中,但是我得到了同样的错误。 请帮我。谢谢!
答案 0 :(得分:1)
这一定是因为您正在尝试显示指向不存在的轮询实例的链接。我的意思是,在你的模板中:
{{1}}
我打赌你的instance.poll.id是None,因此django找不到任何合适的urlconf(你可以看到,r'^(?P \ d +)/ vote / $'至少要求一个数字作为参数)。作为测试:您可以再次尝试,通过注释掉该行并显示{{instance.poll}}吗?是否显示任何内容?
解决方案:在尝试显示插件之前,必须将有效值设置为instance.poll。