我正在关注从Django官方文档中编写您的第一个Django应用程序,第3部分。
在本教程的一部分,我编辑了 polls / urls.py 文件,如下所示:
from django.conf.urls import url
from polls import views
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'),
]
现在访问结果部分,我已进入此链接:
http://localhost:8000/polls/34/results/
但它显示服务器错误(500)
N.B:其他部分如:
http://localhost:8000/polls/34/
http://localhost:8000/polls/34/vote/
运作良好。
我猜测我的代码中可能存在语法错误。但我找不到任何。
修改
这是我的民意调查目录:
polls/
admin.py
__init__.py
models.py
tests.py
urls.py
views.py
编辑2:
models.py:
mport datetime
from django.db import models
from django.utils import timezone
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return u'%s' % (self.question_text)
def was_published_recently(self):
return self.pub_date >= timezone.now()-datetime.timedelta(days=1)
was_published_recently.admin_order_field = "pub_date"
was_published_recently.boolean = True
was_published_recently.short_description = "Published recently?"
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return u'%s' % (self.choice_text)
views.py:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
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)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpRespones(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
admin.py:
from django.contrib import admin
from polls.models import Choice, Question
# Register your models here.
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets= [
(None, {'fields': ['question_text']}),
('Date information', {'fields':['pub_date'],
'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date',
'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin)
mysite的/ setting.py:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
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/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_bl4&0u5ph5=1l**)*8nbgta-sakxt@z8rd$fwj=abt4frj5#6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['localhost']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Dhaka'
USE_I18N = True
USE_L10N = True
USE_TZ = True
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'
答案 0 :(得分:1)
只是一个小错误,但如果这个修好了我会接受答案:):
您在错误方法中返回HttpRespones
而不是return HttpResponse
。顺便说一下,如果您使用的是“实时”服务器而不是Django玩具服务器,您应该在日志中看到一个SyntaxError,例如:在Mac上的/var/log/apache2/error_log
。
答案 1 :(得分:0)
您在settings.py中将DEBUG设置为False,但您没有更改ALLOWED_HOSTS变量以包含您的域名。作为一项安全措施,每当您关闭调试时,您必须明确说明允许从哪个域名调用该域名。
ALLOWED_HOSTS = [&#39; yourdomainname.com&#39;]