filters.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. """
  2. This encapsulates the logic for displaying filters in the Django admin.
  3. Filters are specified in models with the "list_filter" option.
  4. Each filter subclass knows how to display a filter for a field that passes a
  5. certain test -- e.g. being a DateField or ForeignKey.
  6. """
  7. import datetime
  8. from django.contrib.admin.options import IncorrectLookupParameters
  9. from django.contrib.admin.utils import (
  10. get_limit_choices_to_from_path, get_model_from_relation,
  11. prepare_lookup_value, reverse_field_path,
  12. )
  13. from django.core.exceptions import ImproperlyConfigured, ValidationError
  14. from django.db import models
  15. from django.db.models.fields.related import ForeignObjectRel, ManyToManyField
  16. from django.utils import timezone
  17. from django.utils.encoding import force_text, smart_text
  18. from django.utils.translation import ugettext_lazy as _
  19. class ListFilter(object):
  20. title = None # Human-readable title to appear in the right sidebar.
  21. template = 'admin/filter.html'
  22. def __init__(self, request, params, model, model_admin):
  23. # This dictionary will eventually contain the request's query string
  24. # parameters actually used by this filter.
  25. self.used_parameters = {}
  26. if self.title is None:
  27. raise ImproperlyConfigured(
  28. "The list filter '%s' does not specify "
  29. "a 'title'." % self.__class__.__name__)
  30. def has_output(self):
  31. """
  32. Returns True if some choices would be output for this filter.
  33. """
  34. raise NotImplementedError('subclasses of ListFilter must provide a has_output() method')
  35. def choices(self, cl):
  36. """
  37. Returns choices ready to be output in the template.
  38. """
  39. raise NotImplementedError('subclasses of ListFilter must provide a choices() method')
  40. def queryset(self, request, queryset):
  41. """
  42. Returns the filtered queryset.
  43. """
  44. raise NotImplementedError('subclasses of ListFilter must provide a queryset() method')
  45. def expected_parameters(self):
  46. """
  47. Returns the list of parameter names that are expected from the
  48. request's query string and that will be used by this filter.
  49. """
  50. raise NotImplementedError('subclasses of ListFilter must provide an expected_parameters() method')
  51. class SimpleListFilter(ListFilter):
  52. # The parameter that should be used in the query string for that filter.
  53. parameter_name = None
  54. def __init__(self, request, params, model, model_admin):
  55. super(SimpleListFilter, self).__init__(
  56. request, params, model, model_admin)
  57. if self.parameter_name is None:
  58. raise ImproperlyConfigured(
  59. "The list filter '%s' does not specify "
  60. "a 'parameter_name'." % self.__class__.__name__)
  61. if self.parameter_name in params:
  62. value = params.pop(self.parameter_name)
  63. self.used_parameters[self.parameter_name] = value
  64. lookup_choices = self.lookups(request, model_admin)
  65. if lookup_choices is None:
  66. lookup_choices = ()
  67. self.lookup_choices = list(lookup_choices)
  68. def has_output(self):
  69. return len(self.lookup_choices) > 0
  70. def value(self):
  71. """
  72. Returns the value (in string format) provided in the request's
  73. query string for this filter, if any. If the value wasn't provided then
  74. returns None.
  75. """
  76. return self.used_parameters.get(self.parameter_name, None)
  77. def lookups(self, request, model_admin):
  78. """
  79. Must be overridden to return a list of tuples (value, verbose value)
  80. """
  81. raise NotImplementedError(
  82. 'The SimpleListFilter.lookups() method must be overridden to '
  83. 'return a list of tuples (value, verbose value)')
  84. def expected_parameters(self):
  85. return [self.parameter_name]
  86. def choices(self, cl):
  87. yield {
  88. 'selected': self.value() is None,
  89. 'query_string': cl.get_query_string({}, [self.parameter_name]),
  90. 'display': _('All'),
  91. }
  92. for lookup, title in self.lookup_choices:
  93. yield {
  94. 'selected': self.value() == force_text(lookup),
  95. 'query_string': cl.get_query_string({
  96. self.parameter_name: lookup,
  97. }, []),
  98. 'display': title,
  99. }
  100. class FieldListFilter(ListFilter):
  101. _field_list_filters = []
  102. _take_priority_index = 0
  103. def __init__(self, field, request, params, model, model_admin, field_path):
  104. self.field = field
  105. self.field_path = field_path
  106. self.title = getattr(field, 'verbose_name', field_path)
  107. super(FieldListFilter, self).__init__(
  108. request, params, model, model_admin)
  109. for p in self.expected_parameters():
  110. if p in params:
  111. value = params.pop(p)
  112. self.used_parameters[p] = prepare_lookup_value(p, value)
  113. def has_output(self):
  114. return True
  115. def queryset(self, request, queryset):
  116. try:
  117. return queryset.filter(**self.used_parameters)
  118. except ValidationError as e:
  119. raise IncorrectLookupParameters(e)
  120. @classmethod
  121. def register(cls, test, list_filter_class, take_priority=False):
  122. if take_priority:
  123. # This is to allow overriding the default filters for certain types
  124. # of fields with some custom filters. The first found in the list
  125. # is used in priority.
  126. cls._field_list_filters.insert(
  127. cls._take_priority_index, (test, list_filter_class))
  128. cls._take_priority_index += 1
  129. else:
  130. cls._field_list_filters.append((test, list_filter_class))
  131. @classmethod
  132. def create(cls, field, request, params, model, model_admin, field_path):
  133. for test, list_filter_class in cls._field_list_filters:
  134. if not test(field):
  135. continue
  136. return list_filter_class(field, request, params,
  137. model, model_admin, field_path=field_path)
  138. class RelatedFieldListFilter(FieldListFilter):
  139. def __init__(self, field, request, params, model, model_admin, field_path):
  140. other_model = get_model_from_relation(field)
  141. if hasattr(field, 'rel'):
  142. rel_name = field.rel.get_related_field().name
  143. else:
  144. rel_name = other_model._meta.pk.name
  145. self.lookup_kwarg = '%s__%s__exact' % (field_path, rel_name)
  146. self.lookup_kwarg_isnull = '%s__isnull' % field_path
  147. self.lookup_val = request.GET.get(self.lookup_kwarg)
  148. self.lookup_val_isnull = request.GET.get(self.lookup_kwarg_isnull)
  149. self.lookup_choices = self.field_choices(field, request, model_admin)
  150. super(RelatedFieldListFilter, self).__init__(
  151. field, request, params, model, model_admin, field_path)
  152. if hasattr(field, 'verbose_name'):
  153. self.lookup_title = field.verbose_name
  154. else:
  155. self.lookup_title = other_model._meta.verbose_name
  156. self.title = self.lookup_title
  157. def has_output(self):
  158. if (isinstance(self.field, ForeignObjectRel) and
  159. self.field.field.null or hasattr(self.field, 'rel') and
  160. self.field.null):
  161. extra = 1
  162. else:
  163. extra = 0
  164. return len(self.lookup_choices) + extra > 1
  165. def expected_parameters(self):
  166. return [self.lookup_kwarg, self.lookup_kwarg_isnull]
  167. def field_choices(self, field, request, model_admin):
  168. return field.get_choices(include_blank=False)
  169. def choices(self, cl):
  170. from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
  171. yield {
  172. 'selected': self.lookup_val is None and not self.lookup_val_isnull,
  173. 'query_string': cl.get_query_string({},
  174. [self.lookup_kwarg, self.lookup_kwarg_isnull]),
  175. 'display': _('All'),
  176. }
  177. for pk_val, val in self.lookup_choices:
  178. yield {
  179. 'selected': self.lookup_val == smart_text(pk_val),
  180. 'query_string': cl.get_query_string({
  181. self.lookup_kwarg: pk_val,
  182. }, [self.lookup_kwarg_isnull]),
  183. 'display': val,
  184. }
  185. if (isinstance(self.field, ForeignObjectRel) and
  186. (self.field.field.null or isinstance(self.field.field, ManyToManyField)) or
  187. hasattr(self.field, 'rel') and (self.field.null or isinstance(self.field, ManyToManyField))):
  188. yield {
  189. 'selected': bool(self.lookup_val_isnull),
  190. 'query_string': cl.get_query_string({
  191. self.lookup_kwarg_isnull: 'True',
  192. }, [self.lookup_kwarg]),
  193. 'display': EMPTY_CHANGELIST_VALUE,
  194. }
  195. FieldListFilter.register(lambda f: (
  196. bool(f.rel) if hasattr(f, 'rel') else
  197. isinstance(f, ForeignObjectRel)), RelatedFieldListFilter)
  198. class BooleanFieldListFilter(FieldListFilter):
  199. def __init__(self, field, request, params, model, model_admin, field_path):
  200. self.lookup_kwarg = '%s__exact' % field_path
  201. self.lookup_kwarg2 = '%s__isnull' % field_path
  202. self.lookup_val = request.GET.get(self.lookup_kwarg, None)
  203. self.lookup_val2 = request.GET.get(self.lookup_kwarg2, None)
  204. super(BooleanFieldListFilter, self).__init__(field,
  205. request, params, model, model_admin, field_path)
  206. def expected_parameters(self):
  207. return [self.lookup_kwarg, self.lookup_kwarg2]
  208. def choices(self, cl):
  209. for lookup, title in (
  210. (None, _('All')),
  211. ('1', _('Yes')),
  212. ('0', _('No'))):
  213. yield {
  214. 'selected': self.lookup_val == lookup and not self.lookup_val2,
  215. 'query_string': cl.get_query_string({
  216. self.lookup_kwarg: lookup,
  217. }, [self.lookup_kwarg2]),
  218. 'display': title,
  219. }
  220. if isinstance(self.field, models.NullBooleanField):
  221. yield {
  222. 'selected': self.lookup_val2 == 'True',
  223. 'query_string': cl.get_query_string({
  224. self.lookup_kwarg2: 'True',
  225. }, [self.lookup_kwarg]),
  226. 'display': _('Unknown'),
  227. }
  228. FieldListFilter.register(lambda f: isinstance(f,
  229. (models.BooleanField, models.NullBooleanField)), BooleanFieldListFilter)
  230. class ChoicesFieldListFilter(FieldListFilter):
  231. def __init__(self, field, request, params, model, model_admin, field_path):
  232. self.lookup_kwarg = '%s__exact' % field_path
  233. self.lookup_val = request.GET.get(self.lookup_kwarg)
  234. super(ChoicesFieldListFilter, self).__init__(
  235. field, request, params, model, model_admin, field_path)
  236. def expected_parameters(self):
  237. return [self.lookup_kwarg]
  238. def choices(self, cl):
  239. yield {
  240. 'selected': self.lookup_val is None,
  241. 'query_string': cl.get_query_string({}, [self.lookup_kwarg]),
  242. 'display': _('All')
  243. }
  244. for lookup, title in self.field.flatchoices:
  245. yield {
  246. 'selected': smart_text(lookup) == self.lookup_val,
  247. 'query_string': cl.get_query_string({
  248. self.lookup_kwarg: lookup}),
  249. 'display': title,
  250. }
  251. FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldListFilter)
  252. class DateFieldListFilter(FieldListFilter):
  253. def __init__(self, field, request, params, model, model_admin, field_path):
  254. self.field_generic = '%s__' % field_path
  255. self.date_params = {k: v for k, v in params.items()
  256. if k.startswith(self.field_generic)}
  257. now = timezone.now()
  258. # When time zone support is enabled, convert "now" to the user's time
  259. # zone so Django's definition of "Today" matches what the user expects.
  260. if timezone.is_aware(now):
  261. now = timezone.localtime(now)
  262. if isinstance(field, models.DateTimeField):
  263. today = now.replace(hour=0, minute=0, second=0, microsecond=0)
  264. else: # field is a models.DateField
  265. today = now.date()
  266. tomorrow = today + datetime.timedelta(days=1)
  267. if today.month == 12:
  268. next_month = today.replace(year=today.year + 1, month=1, day=1)
  269. else:
  270. next_month = today.replace(month=today.month + 1, day=1)
  271. next_year = today.replace(year=today.year + 1, month=1, day=1)
  272. self.lookup_kwarg_since = '%s__gte' % field_path
  273. self.lookup_kwarg_until = '%s__lt' % field_path
  274. self.links = (
  275. (_('Any date'), {}),
  276. (_('Today'), {
  277. self.lookup_kwarg_since: str(today),
  278. self.lookup_kwarg_until: str(tomorrow),
  279. }),
  280. (_('Past 7 days'), {
  281. self.lookup_kwarg_since: str(today - datetime.timedelta(days=7)),
  282. self.lookup_kwarg_until: str(tomorrow),
  283. }),
  284. (_('This month'), {
  285. self.lookup_kwarg_since: str(today.replace(day=1)),
  286. self.lookup_kwarg_until: str(next_month),
  287. }),
  288. (_('This year'), {
  289. self.lookup_kwarg_since: str(today.replace(month=1, day=1)),
  290. self.lookup_kwarg_until: str(next_year),
  291. }),
  292. )
  293. super(DateFieldListFilter, self).__init__(
  294. field, request, params, model, model_admin, field_path)
  295. def expected_parameters(self):
  296. return [self.lookup_kwarg_since, self.lookup_kwarg_until]
  297. def choices(self, cl):
  298. for title, param_dict in self.links:
  299. yield {
  300. 'selected': self.date_params == param_dict,
  301. 'query_string': cl.get_query_string(
  302. param_dict, [self.field_generic]),
  303. 'display': title,
  304. }
  305. FieldListFilter.register(
  306. lambda f: isinstance(f, models.DateField), DateFieldListFilter)
  307. # This should be registered last, because it's a last resort. For example,
  308. # if a field is eligible to use the BooleanFieldListFilter, that'd be much
  309. # more appropriate, and the AllValuesFieldListFilter won't get used for it.
  310. class AllValuesFieldListFilter(FieldListFilter):
  311. def __init__(self, field, request, params, model, model_admin, field_path):
  312. self.lookup_kwarg = field_path
  313. self.lookup_kwarg_isnull = '%s__isnull' % field_path
  314. self.lookup_val = request.GET.get(self.lookup_kwarg, None)
  315. self.lookup_val_isnull = request.GET.get(self.lookup_kwarg_isnull,
  316. None)
  317. parent_model, reverse_path = reverse_field_path(model, field_path)
  318. # Obey parent ModelAdmin queryset when deciding which options to show
  319. if model == parent_model:
  320. queryset = model_admin.get_queryset(request)
  321. else:
  322. queryset = parent_model._default_manager.all()
  323. # optional feature: limit choices base on existing relationships
  324. # queryset = queryset.complex_filter(
  325. # {'%s__isnull' % reverse_path: False})
  326. limit_choices_to = get_limit_choices_to_from_path(model, field_path)
  327. queryset = queryset.filter(limit_choices_to)
  328. self.lookup_choices = (queryset
  329. .distinct()
  330. .order_by(field.name)
  331. .values_list(field.name, flat=True))
  332. super(AllValuesFieldListFilter, self).__init__(
  333. field, request, params, model, model_admin, field_path)
  334. def expected_parameters(self):
  335. return [self.lookup_kwarg, self.lookup_kwarg_isnull]
  336. def choices(self, cl):
  337. from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
  338. yield {
  339. 'selected': (self.lookup_val is None
  340. and self.lookup_val_isnull is None),
  341. 'query_string': cl.get_query_string({},
  342. [self.lookup_kwarg, self.lookup_kwarg_isnull]),
  343. 'display': _('All'),
  344. }
  345. include_none = False
  346. for val in self.lookup_choices:
  347. if val is None:
  348. include_none = True
  349. continue
  350. val = smart_text(val)
  351. yield {
  352. 'selected': self.lookup_val == val,
  353. 'query_string': cl.get_query_string({
  354. self.lookup_kwarg: val,
  355. }, [self.lookup_kwarg_isnull]),
  356. 'display': val,
  357. }
  358. if include_none:
  359. yield {
  360. 'selected': bool(self.lookup_val_isnull),
  361. 'query_string': cl.get_query_string({
  362. self.lookup_kwarg_isnull: 'True',
  363. }, [self.lookup_kwarg]),
  364. 'display': EMPTY_CHANGELIST_VALUE,
  365. }
  366. FieldListFilter.register(lambda f: True, AllValuesFieldListFilter)
  367. class RelatedOnlyFieldListFilter(RelatedFieldListFilter):
  368. def field_choices(self, field, request, model_admin):
  369. limit_choices_to = {'pk__in': set(model_admin.get_queryset(request).values_list(field.name, flat=True))}
  370. return field.get_choices(include_blank=False, limit_choices_to=limit_choices_to)