Skip to main content
 首页 » 编程设计

python之DjangoCMS 教程 : Plugins 上的 NoReverseMatch 错误

2025年05月04日35yjmyzz

我正在做 DjangoCMS 教程:http://django-cms.readthedocs.org/en/latest/introduction/plugins.html

到目前为止一切都很好,但是当我尝试将轮询插件添加到某个占位符时出现以下错误:

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" /> 

View :

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"> 行

投票应用的u​​rls.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 放在单引号内,但我得到了同样的错误。 请帮我。谢谢!

请您参考如下方法:

这一定是因为您试图显示指向不存在的轮询实例的链接。我的意思是,在您的模板中:

<form action="{% url 'polls:vote' instance.poll.id %}" method="post"> 

我打赌你的 instance.poll.id 是 None,因此 django 找不到任何合适的 urlconf(如你所见,r'^(?P\d+)/vote/$' 至少要求 一个 数字作为参数)。作为测试:您可以通过注释掉该行并仅显示 {{ instance.poll }} 再试一次吗?它是否显示任何内容?

解决方案:在尝试显示插件之前,您必须为 instance.poll 设置一个有效值。