是否可以在同一实例上将 Django Sites Framework 与多个站点一起使用?

Is it possible to use the Django Sites Framework with multiple Sites on the same instance?

我已经按照站点框架文档的建议定义了多个站点。

我明白,如果我 运行 我的应用程序的多个实例,每个实例都有不同的设置文件(不同 SITE_ID),Django 将始终知道要使用哪个站点。

我试图做的是 运行 单个实例,其中有多个站点可用,应根据站点的当前 url 选择正确的站点。

站点 documentation 声明:

The SITE_ID setting specifies the database ID of the Site object associated with that particular settings file. If the setting is omitted, the get_current_site() function will try to get the current site by comparing the domain with the host name from the request.get_host() method.

所以我尝试从我的 settings.py 中删除 SITE_ID 并希望 Django 会检查域以找到如上所述的当前站点,但是失败并出现以下异常:

You're using the Django "sites framework" without having set the SITE_ID setting. Create a site in your database and set the SITE_ID setting or pass a request to Site.objects.get_current() to fix this error.

所以看起来虽然文档另有建议,但这个设置是不可忽略的

我知道,当没有请求对象可用于查找当前站点时,像这样使用站点框架会导致问题,但这在我的应用程序上下文中应该不是问题。

是否可以通过仅检查应用程序的当前域来使用站点框架而不对设置文件中的 SITE_ID 进行硬编码?

我正在使用 Django 版本 1.9.9 和 Python 3.4.3

您需要向 "check the current domain" 提出请求 - 正如错误消息中明确提到的那样:

or pass a request to Site.objects.get_current()

否则代码如何知道 "current domain"?

最好的解决方案是简单地添加 Sites framework middleware:

'django.contrib.sites.middleware.CurrentSiteMiddleware'

这会在每次请求时自动将请求对象传递给 Site.objects.get_current()。