我开始学习Django,我正在实现“测试视图”功能。 当我在shell中使用测试客户端时,发生如下异常。Django无效的HTTP_HOST标头:'testserver'。您可能需要添加u'testserver'ALLOWED_HOSTS
Invalid HTTP_HOST header: 'testserver'. You may need to add u'testserver' to 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.I想我应该在settings.py声明ALLOWED_HOSTS,但我怎么能? 我使用$ python manage.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
是你的调试假的? – Exprator
感谢您与我联系。是的,调试是错误 –
然后在允许的主机放127.0.0.1,本地主机和检查 – Exprator