I'm looking for the same functionality as the CurrentSiteManager provides but without having to specify SITE_ID in settings.py as the CurrentSiteManager requires. Information about the current site should come from the request. My take on the problem would be to make a custom manager, but is there something I'm missing? What would be a good way of doing this? It seems quite trivial that the CurrentSiteManager should provide this functionality. Would it make sense to submit a feature request?
-
The code you linked to is over a year old - the [latest version](https://github.com/django/django/blob/2e1f674897e89bbc69a389696773aebfec601916/django/contrib/sites/models.py) of the `SiteManager` implements a host-based approach which gets the current site from the hostname if no SITE_ID is defined. – solarissmoke May 03 '18 at 16:20
-
See also https://github.com/django/django/pull/3293 – solarissmoke May 03 '18 at 16:31
-
@solarissmoke: I'm already using the SiteManager, but the CurrentSiteManager doesn't provide that functionality. I want an equivalent to User.objects.all() that only returns users associated to the current site (usually User.on_site.all(), but that requires SITE_ID to be set). – deni May 03 '18 at 17:48
-
Ah, I see. Thanks for clarifying. I have posted an answer that I think explains why this isn't something that Django can do for you. – solarissmoke May 04 '18 at 02:40
1 Answers
You write:
Information about the current site should come from the request.
There is a big assumption here, which is that the manager will always have a request context available.
This isn't an assumption that Django can make: any generic model manager must work outside of a request context because there are all sorts of cases where a request context isn't available - e.g., management commands, migrations, tasks, etc. Even if you are in the context of a request, your manager has no knowledge of this unless you explicitly pass it to any method on the manager (i.e., you need those methods to accept a request
argument). This is why CurrentSiteManager
requires a SITE_ID
:
The CurrentSiteManager is only usable when the
SITE_ID
setting is defined in your settings.
If you do want to filter objects within a request context, then Django provides the CurrentSiteMiddleware
to add the current site to all requests. Within your views you can then filter objects on this site
.
There are examples of projects that have implemented a custom CurrentSiteManager
that does what you're asking for - the one that comes to mind is Mezzanine which you may be able to borrow from (note that it involves messing around with thread locals, and still requires a fallback to a SITE_ID
setting).

- 30,039
- 14
- 71
- 73