我正在关注Django教程并完成了此页面的一半:Django tutorial
我收到错误' NoReverseMatch'异常值为"反向'投票'有参数'(无,)'和关键字参数' {}'未找到。尝试了1种模式:['民意调查/(?P [0-9] +)/投票/ $']"。我已经完成并试图尽可能地检查类型,但解决这个问题的任何帮助都会很棒。我将相关代码放在下面,但如果您需要任何其他代码,请告诉我。感谢
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
admin.py 来自django.contrib import admin 来自.models导入问题 #在这里注册您的模型。 admin.site.register(问题) urls.py 来自django.conf.urls import 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'),
]