Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

filters.py 17KB

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