2013-11-09 53 views
202

我是django-1.6的新手。当我用DEBUG = True运行django服务器时,它运行得非常完美。但是,当我在设置文件更改DEBUGFalse,那么服务器停止,并让在命令提示符下以下错误:当DEBUG = False时,Django提供了错误的请求(400)

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. 

后,我改变了ALLOWED_HOSTS["http://127.0.0.1:8000",],在浏览器中我得到的错误:

Bad Request (400) 

是否有可能在没有调试模式下运行Django?

+0

有一点要记住:不要在'ALLOWED_HOSTS'中加'http'或'https' – shellbye

回答

350

ALLOWED_HOSTS list应该包含完全合格主机名网址。离开端口和协议。如果使用的是127.0.0.1,我想补充localhost到列表中太:

ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] 

你也可以使用*匹配任何主持人:

ALLOWED_HOSTS = ['*'] 

引用文档:

Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com , www.example.com , and any other subdomain of example.com . A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE_CLASSES).

大胆重点我的

您收到的400状态响应是由于您的主机标头与该列表中的任何值不匹配导致SuspiciousOperation exception被触发。

+2

感谢它的工作,但是当我设置False时,出现一个问题,所有静态文件显示为404。明白为什么没有找到 – MegaBytes

+0

@MegaBytes:对不起,我不知道这可能是什么。 –

+1

你可以建议我怎么做,因为我的项目正在进行生产。 – MegaBytes

2

我有同样的问题,我通过设置ALLOWED_HOSTS = ['*']与你必须改变环境的配置是这样的虚拟路径上的静态图像来解决问题固定它:

虚拟路径                                 目录

/静态/                                                    的/ opt /蟒蛇/电流/应用/ yourpj /静态/
/media/                                           的/ opt /蟒蛇/电流/应用/新/媒体/

我希望它可以帮助你。

PD:抱歉我的英语不好。

-1

导航到设置和定位base.py文件 将允许主机 ALLOWED_HOSTS = [“*”]

+1

不要重复接受的答案。删除它以保持清洁论坛 – WoodChopper

+0

不回答这样的问题,评论它 –

2

对于我来说,我通过不设置USE_X_FORWARDED_HOST到真正得到这个错误。从文档:

This should only be enabled if a proxy which sets this header is in use.

我的托管服务wrote明确自己的文档中,这个设置必须使用,而我,如果我忘了得到这400错误。

+0

这是必要的,如果ALLOWED_HOSTS = ['*']? –

+1

我认为ALLOWED_HOSTS会阻止整个主机。 USE_X_FORWARDED_HOST仅确定是否使用HTTP标头。 – Keith

1

随着DEBUG = False在你的设置文件中,你还需要设置ALLOWED_HOST列表。 尝试包括ALLOWED_HOST = ['127.0.0.1', 'localhost', 'www.yourdomain.com']

否则,您可能会收到来自django的错误请求(400)错误。