NoReverseMatch at / polls /

时间:2017-08-25 12:23:08

标签: python django

我正在通过浏览Django教程来建立网络。 我收到了一个错误:

  

NoReverseMatch at / polls / Reverse for' index'没有参数没有   找到。尝试了1种模式:[' $ /']。

error

Traceback说

Traceback:

File "/Users/XXX/django/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
  130.                 response = self.process_exception_by_middleware(e, request)

File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
  128.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/XXX/djangostudy/polls/views.py" in index
  23.         'questions': Question.objects.all(),

File "/Users/XXX/django/django/shortcuts.py" in render
  36.     content = loader.render_to_string(template_name, context, request, using=using)

File "/Users/XXX/django/django/template/loader.py" in render_to_string
  62.     return template.render(context, request)

File "/Users/XXX/django/django/template/backends/django.py" in render
  61.             return self.template.render(context)

File "/Users/XXX/django/django/template/base.py" in render
  175.                     return self._render(context)

File "/Users/XXX/django/django/template/base.py" in _render
  167.         return self.nodelist.render(context)

File "/Users/XXX/django/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/Users/XXX/django/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/Users/XXX/django/django/template/loader_tags.py" in render
  155.             return compiled_parent._render(context)

File "/Users/XXX/django/django/template/base.py" in _render
  167.         return self.nodelist.render(context)

File "/Users/XXX/django/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/Users/XXX/django/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/Users/XXX/django/django/template/loader_tags.py" in render
  155.             return compiled_parent._render(context)

File "/Users/XXX/django/django/template/base.py" in _render
  167.         return self.nodelist.render(context)

File "/Users/XXX/django/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/Users/XXX/django/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/Users/XXX/django/django/template/defaulttags.py" in render
  447.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "/Users/XXX/django/django/urls/base.py" in reverse
  87.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "/Users/XXX/django/django/urls/resolvers.py" in _reverse_with_prefix
  488.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /polls/
Exception Value: Reverse for 'index' with no arguments not found. 1 pattern(s) tried: ['$/']

我在base.html中写道,与父母的应用程序相同,就像

{% load staticfiles %}
{% load bootstrap3 %}
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Starter Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="static/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
body {
  padding-top: 50px;
}
    </style>
  </head>

  <body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="{% url 'index' %}">Tutorial</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="{% block nav_polls %}{% endblock %}"><a href="{% url 'polls:index' %}">polls</a></li>
            <li class=""><a href="{% url 'admin:index' %}">admin</a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>

    <div class="container">
    {% bootstrap_messages messages %}
    {% block contents %}{% endblock %}
    </div><!-- /.container -->
    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
  </body>
</html>

父母的urls.py&#39;目录是

from django.conf.urls import include,url
from django.contrib import admin
from polls.views import index

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^polls/',include('polls.urls')),
    url(r'^$/',index,name='index'),
]

urls.py名为民意调查的子应用程序就像

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

app_name="polls"
urlpatterns = [
    url(r'^$',views.index,name='index'),
    url(r'(?P<pk>\d+)/$', views.detail, name='poll_detail'),
    url(r'(?P<pk>\d+)/vote$', views.vote, name='poll_vote'),
    url(r'(?P<pk>\d+)/results$', views.results, name='poll_results'),
    url(r'^$',TemplateView.as_view(template_name='app/index.html'),name='app_index'),
    url(r'^form$', views.form_test),
]

我真的无法理解为什么会发生这种错误。指定"{% url 'index' %}"错误的方式是什么?我该如何解决这个问题?

我的views.py就像

from django.shortcuts import render
from django.urls import reverse_lazy
from django.utils.html import mark_safe
from .models import Question
from django.http import HttpResponse
from django.shortcuts import Http404
from django.shortcuts import get_object_or_404,redirect
from .models import Choice
from django.views.generic import TemplateView
from django.views.generic import DetailView
from django.views.generic import ListView
from .forms import MyForm
from .forms import VoteForm
from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin
from django.shortcuts import resolve_url

def index(request):
    return render(request,'polls/index.html',{
        'questions': Question.objects.all(),
    })

def vote(request,pk):
    question = get_object_or_404(Question,pk=pk)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError,Choice.DoesNotExist):
        return render(request,'poll/detail.html',{
            'question':question,
            'error_message':"You didn't select a choice",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return redirect('index')
    return redirect('poll_results', pk)
    # pass

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

class FormTest(FormView):
   form_class = MyForm
   template_name = 'polls/form.html'
   success_url = reverse_lazy('polls:index')
form_test = FormTest.as_view()

class Detail(SingleObjectMixin,FormView):
    model = Question
    form_class = VoteForm
    context_object_name = 'question'
    template_name = 'polls/detail.html'

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super().post(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super().post(request, *args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['question'] = self.object
        return kwargs

    def form_valid(self, form):
        form.vote()
        return super().form_valid(form)

    def get_success_url(self):
        return resolve_url('polls:results',self.kwargs['pk'])

detail = Detail.as_view()

我的目录是 directory

3 个答案:

答案 0 :(得分:1)

urls.py 文件中,不同视图的网址相同。 Django只会考虑第一个网址。 删除

        url(r'^$/',index,name='index'),
来自父母的

将解决问题

答案 1 :(得分:0)

您有重复的网址,并且网址名称为index的副本,请尝试修复

例如在polls.urls

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='app/index.html'), name='app_index'),
    url(r'(?P<pk>\d+)/$', views.detail, name='poll_detail'),
    url(r'(?P<pk>\d+)/vote$', views.vote, name='poll_vote'),
    url(r'(?P<pk>\d+)/results$', views.results, name='poll_results'),
    url(r'^form$', views.form_test),
]
在urls.py中

urlpatterns = [
    url(r'^$',index,name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^polls/',include('polls.urls')),
]

urls(&#34; Django按顺序遍历每个URL模式,并在第一个匹配请求的URL的位置停止。&#34;)

答案 2 :(得分:0)

嗯,由于您正在使用应用,因此您不会有重复的网址,因此问题出现在url(r'^$/',,错误的正确方法是url(r'^$'原因是你总是必须在URL的末尾设置$,试试并告诉我