问题描述
有什么好方法可以根据URL中的域名在settings.py中动态设置SITE_ID?
What is a good way to dynamically set SITE_ID in settings.py based on domain name in URL?
我有一个应用程序将使用太多的域名(基于城市)运行,每个域名都无法使用自定义settings.py文件.
I have an app that will be running with too many domain names (city based) that a custom settings.py file for each domain is just not doable.
有没有办法动态设置它?
Is there a way to set it dynamically?
推荐答案
您可以执行一个自定义中间件,该中间件读取请求并设置SITE_ID.我在我的一个网站上使用此代码:
You can do a custom middleware which reads the request and sets the SITE_ID. I use this code on one of my sites:
class SiteMiddleware(object):
def process_request(self, request):
try:
current_site = Site.objects.get(domain=request.get_host())
except Site.DoesNotExist:
current_site = Site.objects.get(id=settings.DEFAULT_SITE_ID)
request.current_site = current_site
settings.SITE_ID = current_site.id
您应该查看中间件的Django文档,以了解如何添加自己的中间件. https://docs.djangoproject.com/en/dev/topics/http/middleware/
You should look at Django's documentation on middleware to find out how to add your own middleware. https://docs.djangoproject.com/en/dev/topics/http/middleware/
这篇关于Django:是否根据URL在settings.py中动态设置SITE_ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!