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

╄→尐↘猪︶ㄣ 提交于 2019-12-10 10:49:49

问题


I have defined multiple sites as the documentation of the Site Framework suggested.

I understand that if I would run mulitple instances of my application with each of them having a different settings file (different SITE_ID), Django would always know which Site to use.

What I was trying to do is to run a single instance, where multiple sites are available, and the right Site should be chosen depending on the current url of the site.

The Sites documentation states:

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.

So I tried to remove the SITE_ID from my settings.py and was hoping that Django would check the domain to find the current Site as stated above, howewer this fails with the following exception:

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.

So it seems like although the documentation suggests otherwise, this setting is not ommitable

I understand that using the Sites Framework like this would lead to problems when there is no Request object available to find the current Site, but this should not be a problem in the context of my application.

Is it possible to use the Sites Framework without hard-coding the SITE_ID in the settings file by just checking the current domain of the application?

I am using Django Version 1.9.9 with Python 3.4.3


回答1:


To "check the current domain" you need to have a request - as clearly mentionned in the error message :

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

Else how would the code know the "current domain" ?




回答2:


The best solution is to simply add the Sites framework middleware:

'django.contrib.sites.middleware.CurrentSiteMiddleware'

This automatically passes a request object to Site.objects.get_current() on every request.



来源:https://stackoverflow.com/questions/41934828/is-it-possible-to-use-the-django-sites-framework-with-multiple-sites-on-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!