Django无效的HTTP_HOST标头:'testserver'.您可能需要将u'testserver'添加到ALLOWED_HOSTS

Yui*_*nko 14 python django

我开始学习Django,我正在实现"测试视图"功能.当我在shell中使用test Client时,异常发生如下.

无效的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
Run Code Online (Sandbox Code Playgroud)

在本教程中,应该出现404,但是我得到400.当我继续运行命令时,发生了同样的异常.

>>> response = client.get(reverse('polls:index'))
>>> response.status_code
400
Run Code Online (Sandbox Code Playgroud)

但结果必须是200.我想我应该在settings.py中声明ALLOWED_HOSTS,但我怎么办?我使用$ python manage.py runserver在localhost上运行服务器.

我想知道原因和解决方案.

这是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
Run Code Online (Sandbox Code Playgroud)

Exp*_*tor 21

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
Run Code Online (Sandbox Code Playgroud)

这样说吧

之后重新启动服务器


小智 9

ALLOWED_HOSTS = ['XXX.iptime.org', 'localhost', '127.0.0.1', 'testserver']


# 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',
]
Run Code Online (Sandbox Code Playgroud)


cri*_*ter 9

添加“testserver”、“localhost”或“127.0.0.1”对我来说不起作用(Django >3.1)。

所做的是使用不同的服务器名称启动客户端:

c = Client(SERVER_NAME='localhost')
Run Code Online (Sandbox Code Playgroud)

请注意,我收到一个错误,提到我需要添加“testserver”,但我使用“localhost”启动客户端。


Ous*_*aad 5

你应该这样编辑它:

ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', 'testserver', ]