Skip to main content
 首页 » 编程设计

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

2024年08月21日31qlqwjy

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

我知道如果我运行我的应用程序的多个实例,每个实例都有不同的设置文件(不同的 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. 

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

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

是否可以通过仅检查应用程序的当前域来使用 Sites Framework 而无需在设置文件中硬编码 SITE_ID?

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

请您参考如下方法:

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

'django.contrib.sites.middleware.CurrentSiteMiddleware' 

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