简体   繁体   中英

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

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

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.

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" ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM