I started learning Django, I'm in the middle of implementing "Test a view" functionality. When I use test Client in the shell, the exception has occurred as follows.
Invalid HTTP_HOST header: 'testserver'. You may need to add u'testserver' to ALLOWED_HOSTS.
I run the command in the shell as follows.
>>> 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
In the tutorial, 404 should be appeared, but I get 400. When I continue running the command as follows, same exception has occurred.
>>> response = client.get(reverse('polls:index')) >>> response.status_code 400
but the result must be 200.I guess I should declare ALLOWED_HOSTS in the settings.py, but how can I? I run the server on localhost using $python manage.py runserver.
I wanna know the reason and solution.
Here is settings.py as follows.
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
Edit the following line in your settings.py
file:
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
Restart your server afterwards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With