我正在关注Django教程并且已经完成了这个页面的一半:Django tutorial

我得到错误'NoReverseMatch',异常值为“反向'投票',参数'(无,)'和关键字参数'{}'未找到.1模式尝试:['polls /(?P [0-9])/ vote / $']“ . 我已经完成并试图尽可能地检查类型,但解决这个问题的任何帮助都会很棒 . 我将相关代码放在下面,但如果您需要任何其他代码,请告诉我 . 谢谢

views.py

from django.shortcuts import get_object_or_404,render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import choice, question
from django.template import loader

##def index(request):
##    return HttpResponse("Hello World. You're at the polls index.")

##def detail(request, question_id):
##    return HttpResponse("You're looking at question %s." % question_id)
##    try:
##        Question = question.objects.get(pk=question_id)
##    except question.DoesNotExist:
##        raise Http404("Question does not exist")
##    return render(request, 'polls/detail.html',{'Question':Question})

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

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

def index(request):
    latestQuestionList = question.objects.order_by('-pubDate')[:5]
    template = loader.get_template('polls/index.html')
    contect = {
        'latestQuestionList': latestQuestionList,
    }
    #output = ', '.join([q.questionText for q in latestQuestionList])
    return HttpResponse(template.render(context, request))

def vote(request, question_id):
    Question = get_object_or_404(Question, pk=question_id)
    try:
        selectedChoice = question.choiceSet.get(pk=request.POST['choice'])
    except (KeyError, choice.DoesNotExist):
            return render(request, 'polls/detail.html', {
                'question': question,
                'error_message': "You didn't select a choice.",
            })
    else:
            selectedChoice.votes += 1
            selectedChoice.save()
            return
    HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

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

settings.py“”“mysite项目的Django设置 .

Generated by 'django-admin startproject' using Django 1.10.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i$8b5*0iugjm2i$&0x2_&e@dpm_chv_c@82-9rkbr1$e7tw_%r'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

models.py来自django.utils导入时区导入日期时间来自django.db导入模型来自django.utils.encoding import *

# Create your models here.

class question(models.Model):
    questionText = models.CharField(max_length=200)
    pubDate = models.DateTimeField('Date published')

    def __str__(self):
        return self.questionText
    def wasPublishedRecently(self):
        return self.pubDate >= timezone.now() - datetime.timedelta(days=1)

class choice(models.Model):
    question = models.ForeignKey(question, on_delete=models.CASCADE)
    choiceText = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choiceText
#ADMIN PASSWORD IS Timberland

来自django.contrib的admin.py从.models导入管理员导入问题#在此处注册您的模型 . 来自django.conf.urls的admin.site.register(question)urls.py导入url,include

from . import views
app_name = 'polls'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
    ]