R找不到“结果”的反向。 “结果”不是有效的视图函数或模式名称

时间:2019-09-12 16:13:18

标签: django

我正在学习django框架,但出现错误“ 反向查找“结果”。 “结果”不是有效的视图函数或模式名称。” 我在这里包括我的代码。

results.py

{% extends "polls/base.html" %}

{% block main_content %}

<h1>{{question.question_text}}</h1>

<ul>
    {% for choice in question.choice_set.all %}
        <li>{{choice.choice_text}} -- {{choice.votes}} vote{{choice.votes|pluralize}}</li>
    {% endfor %}
</ul>

<a href="{% url 'polls:details' question.id }">Vote again</a>
{% endblock%}

这是民意调查应用程序的urls.py文件。

urls.py

from django.conf.urls import url
from . import views

urlpatterns=[
    url(r"^$",views.index,name="index"),  #127.0.0.1:8000/polls
    url(r"^(?P<question_id>[0-9]+)/$",views.details,name="details"),
    url(r"^(?P<question_id>[0-9]+)/results$",views.results,name="result"),
    url(r"^(?P<question_id>[0-9]+)/vote$",views.vote,name="vote"),
]

views.py

from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
# from django.core.urlresolvers import reverse
from .models import Question
from django.urls import reverse


def results(request,question_id):
    question=get_object_or_404(Question,pk=question_id)
    return render(request,"polls/results.html",{"question":question})

def vote(request,question_id):
    question=get_object_or_404(Question,pk=question_id)
    try:
        selected_choice=question.choice_set.get(pk=request.POST['choice'])
    except:
        return render(request,"polls/details.html",{'question':question,"error_message":"Please select a choice"})
    else:
        selected_choice.votes+=1
        selected_choice.save()

        return HttpResponseRedirect(reverse("polls:results",args=(question.id,)))

1 个答案:

答案 0 :(得分:0)

更改

return HttpResponseRedirect(reverse("polls:results",args=(question.id,)))

收件人

return HttpResponseRedirect(reverse("polls:result",args=(question.id,)))

因为它在您的urls.py中定义为

url(r"^(?P<question_id>[0-9]+)/results$",views.results,name="result"),