编程语言
首页 > 编程语言> > python-NoReverseMatch-Django 1.7初学者教程

python-NoReverseMatch-Django 1.7初学者教程

作者:互联网

我正在遵循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只是获取空字符串,而这不会给我错误No Reverse Match的错误提示其他所有内容,只要我尝试访问任何其他URL,它都会将我重定向到主URL,而无需删除现金$,我可以完美地继续使用这些URL.那我做错了什么呢?

这是项目URL:

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%}和方法发布的传递方式有关,所以这是错误< form action =“ {%url'poll :vote'question.id%}“ method =” post“>

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

解决方法:

urls.py中的URL名称是投票,并且您正在搜索poll:vote,对其进行修复:

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

标签:django-templates,django-urls,python,django
来源: https://codeday.me/bug/20191028/1955409.html