NoReverseMatch - Django 1.7初学者教程

时间:2014-12-25 07:26:54

标签: python django django-templates django-urls

我正在关注Django 1.7.1中的begginers教程并收到此错误

Reverse for 'vote' with arguments '(5,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] `poll\templates\poll\detail.html, error at line 12`
经过一些研究后,我发现人们问了类似的问题,有人建议他们应该从普通网址中删除现金$,因为urlloader只是取空字符串,而这并不是我错误没有反向匹配,它混乱了其他一切,每当我尝试到达任何其他网址时,它会将我重定向到主网址,而不会移除现金$我可以完美地继续这些网址。那么我做错了什么呢?

这是项目URLS:

urlpatterns = patterns('',
    url(r'^poll/', include('poll.urls', namespace="poll")),
    url(r'^admin/', include(admin.site.urls)),
)

应用网址:

from django.conf.urls import patterns, url

from poll import views

urlpatterns = patterns('',
    #e.g. /poll/
    url(r'^$', views.IndexView.as_view(), name='index'),
    #e.g. /poll/5/
    url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
    #e.g. /poll/5/results/
    url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
    #e.g. /poll/5/votes/
    url(r'^(?P<question_id>\d+)/votes/$', views.votes, name='votes'),
)

观点:

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from poll.models import Question, Choice


class IndexView(generic.ListView):
    template_name = 'poll/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pup_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'poll/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'poll/results.html'


def votes(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'poll/detail.html', {
            'question': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('poll:results', args=(p.id,)))

另外我想它可能与行为{%URL%}和方法post的传递方式有关,所以这里是错误{{1}中指定的模板文件中的代码行}

如果您还有其他需要,请告诉我,并提前致谢

1 个答案:

答案 0 :(得分:4)

urls.py中的网址名称为votes,您正在搜索poll:vote,请将其修复:

<form action="{% url 'poll:votes' question.id %}" method="post">
                          HERE ^