我开始学习 Django,我正在实现“测试视图”功能。
当我使用测试客户端在shell中,异常发生如下。
无效的 HTTP_HOST 标头:“testserver”。您可能需要将 u'testserver' 添加到 ALLOWED_HOSTS。
我在 shell 中运行命令如下。
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> client = Client()
>>> response = client.get('/')
>>> response.status_code
400
在教程中,应该出现404,但我得到了400。
当我继续运行以下命令时,发生了相同的异常。
>>> response = client.get(reverse('polls:index'))
>>> response.status_code
400
但结果一定是200。我想我应该声明ALLOWED_HOSTS in the 设置.py,但我又能怎样呢?
我使用在本地主机上运行服务器$python 管理.py runserver.
我想知道原因和解决办法。
这里是settings.py如下。
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '8v57o6wyupthi^#41_yfg4vsx6s($1$x0xmu*95_u93wwy0_&u'
DEBUG = True
ALLOWED_HOSTS = [127.0.0.1,'localhost']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
]
.... (MIDDLEWARE)
ROOT_URLCONF = 'tutorial.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 = 'tutorial.wsgi.application'
.... (DATABASES, AUTH_PASSWORD_VALIDATORS)
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True