2014-01-20 10:45:21 +08:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2006-05-22 12:59:22 +08:00
|
|
|
from django.conf import settings
|
2014-01-20 10:45:21 +08:00
|
|
|
from django.core import checks
|
2015-01-02 23:14:23 +08:00
|
|
|
from django.core.exceptions import FieldDoesNotExist
|
2006-05-22 13:17:25 +08:00
|
|
|
from django.db import models
|
2006-05-22 12:59:22 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-05-22 12:59:22 +08:00
|
|
|
class CurrentSiteManager(models.Manager):
|
|
|
|
"Use this to limit objects to those associated with the current site."
|
2014-01-20 10:45:21 +08:00
|
|
|
|
2014-12-13 06:19:58 +08:00
|
|
|
use_in_migrations = True
|
|
|
|
|
2010-10-18 12:56:27 +08:00
|
|
|
def __init__(self, field_name=None):
|
2006-05-22 13:17:25 +08:00
|
|
|
super(CurrentSiteManager, self).__init__()
|
|
|
|
self.__field_name = field_name
|
2013-10-11 04:42:30 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def check(self, **kwargs):
|
|
|
|
errors = super(CurrentSiteManager, self).check(**kwargs)
|
|
|
|
errors.extend(self._check_field_name())
|
|
|
|
return errors
|
2013-10-11 04:42:30 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def _check_field_name(self):
|
|
|
|
field_name = self._get_field_name()
|
2010-10-18 12:56:27 +08:00
|
|
|
try:
|
2014-01-20 10:45:21 +08:00
|
|
|
field = self.model._meta.get_field(field_name)
|
2010-10-18 12:56:27 +08:00
|
|
|
except FieldDoesNotExist:
|
2014-01-20 10:45:21 +08:00
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"CurrentSiteManager could not find a field named '%s'." % field_name,
|
2014-03-03 14:27:22 +08:00
|
|
|
hint=None,
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
|
|
|
id='sites.E001',
|
|
|
|
)
|
|
|
|
]
|
|
|
|
|
|
|
|
if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 14:27:22 +08:00
|
|
|
"CurrentSiteManager cannot use '%s.%s' as it is not a ForeignKey or ManyToManyField." % (
|
2014-01-20 10:45:21 +08:00
|
|
|
self.model._meta.object_name, field_name
|
|
|
|
),
|
|
|
|
hint=None,
|
|
|
|
obj=self,
|
|
|
|
id='sites.E002',
|
|
|
|
)
|
|
|
|
]
|
|
|
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
def _get_field_name(self):
|
|
|
|
""" Return self.__field_name or 'site' or 'sites'. """
|
|
|
|
|
|
|
|
if not self.__field_name:
|
|
|
|
try:
|
|
|
|
self.model._meta.get_field('site')
|
|
|
|
except FieldDoesNotExist:
|
|
|
|
self.__field_name = 'sites'
|
|
|
|
else:
|
|
|
|
self.__field_name = 'site'
|
|
|
|
return self.__field_name
|
2013-10-11 04:42:30 +08:00
|
|
|
|
2013-03-08 22:15:23 +08:00
|
|
|
def get_queryset(self):
|
2014-01-20 10:45:21 +08:00
|
|
|
return super(CurrentSiteManager, self).get_queryset().filter(
|
|
|
|
**{self._get_field_name() + '__id': settings.SITE_ID})
|