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.

main.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. from collections import OrderedDict
  2. from datetime import datetime, timedelta
  3. from django.conf import settings
  4. from django.contrib.admin import FieldListFilter
  5. from django.contrib.admin.exceptions import (
  6. DisallowedModelAdminLookup, DisallowedModelAdminToField,
  7. )
  8. from django.contrib.admin.options import (
  9. IS_POPUP_VAR, TO_FIELD_VAR, IncorrectLookupParameters,
  10. )
  11. from django.contrib.admin.utils import (
  12. get_fields_from_path, lookup_needs_distinct, prepare_lookup_value, quote,
  13. )
  14. from django.core.exceptions import (
  15. FieldDoesNotExist, ImproperlyConfigured, SuspiciousOperation,
  16. )
  17. from django.core.paginator import InvalidPage
  18. from django.db import models
  19. from django.db.models.expressions import Combinable, F, OrderBy
  20. from django.urls import reverse
  21. from django.utils.http import urlencode
  22. from django.utils.timezone import make_aware
  23. from django.utils.translation import gettext
  24. # Changelist settings
  25. ALL_VAR = 'all'
  26. ORDER_VAR = 'o'
  27. ORDER_TYPE_VAR = 'ot'
  28. PAGE_VAR = 'p'
  29. SEARCH_VAR = 'q'
  30. ERROR_FLAG = 'e'
  31. IGNORED_PARAMS = (
  32. ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR, IS_POPUP_VAR, TO_FIELD_VAR)
  33. class ChangeList:
  34. def __init__(self, request, model, list_display, list_display_links,
  35. list_filter, date_hierarchy, search_fields, list_select_related,
  36. list_per_page, list_max_show_all, list_editable, model_admin, sortable_by):
  37. self.model = model
  38. self.opts = model._meta
  39. self.lookup_opts = self.opts
  40. self.root_queryset = model_admin.get_queryset(request)
  41. self.list_display = list_display
  42. self.list_display_links = list_display_links
  43. self.list_filter = list_filter
  44. self.date_hierarchy = date_hierarchy
  45. self.search_fields = search_fields
  46. self.list_select_related = list_select_related
  47. self.list_per_page = list_per_page
  48. self.list_max_show_all = list_max_show_all
  49. self.model_admin = model_admin
  50. self.preserved_filters = model_admin.get_preserved_filters(request)
  51. self.sortable_by = sortable_by
  52. # Get search parameters from the query string.
  53. try:
  54. self.page_num = int(request.GET.get(PAGE_VAR, 0))
  55. except ValueError:
  56. self.page_num = 0
  57. self.show_all = ALL_VAR in request.GET
  58. self.is_popup = IS_POPUP_VAR in request.GET
  59. to_field = request.GET.get(TO_FIELD_VAR)
  60. if to_field and not model_admin.to_field_allowed(request, to_field):
  61. raise DisallowedModelAdminToField("The field %s cannot be referenced." % to_field)
  62. self.to_field = to_field
  63. self.params = dict(request.GET.items())
  64. if PAGE_VAR in self.params:
  65. del self.params[PAGE_VAR]
  66. if ERROR_FLAG in self.params:
  67. del self.params[ERROR_FLAG]
  68. if self.is_popup:
  69. self.list_editable = ()
  70. else:
  71. self.list_editable = list_editable
  72. self.query = request.GET.get(SEARCH_VAR, '')
  73. self.queryset = self.get_queryset(request)
  74. self.get_results(request)
  75. if self.is_popup:
  76. title = gettext('Select %s')
  77. elif self.model_admin.has_change_permission(request):
  78. title = gettext('Select %s to change')
  79. else:
  80. title = gettext('Select %s to view')
  81. self.title = title % self.opts.verbose_name
  82. self.pk_attname = self.lookup_opts.pk.attname
  83. def get_filters_params(self, params=None):
  84. """
  85. Return all params except IGNORED_PARAMS.
  86. """
  87. params = params or self.params
  88. lookup_params = params.copy() # a dictionary of the query string
  89. # Remove all the parameters that are globally and systematically
  90. # ignored.
  91. for ignored in IGNORED_PARAMS:
  92. if ignored in lookup_params:
  93. del lookup_params[ignored]
  94. return lookup_params
  95. def get_filters(self, request):
  96. lookup_params = self.get_filters_params()
  97. use_distinct = False
  98. for key, value in lookup_params.items():
  99. if not self.model_admin.lookup_allowed(key, value):
  100. raise DisallowedModelAdminLookup("Filtering by %s not allowed" % key)
  101. filter_specs = []
  102. for list_filter in self.list_filter:
  103. if callable(list_filter):
  104. # This is simply a custom list filter class.
  105. spec = list_filter(request, lookup_params, self.model, self.model_admin)
  106. else:
  107. field_path = None
  108. if isinstance(list_filter, (tuple, list)):
  109. # This is a custom FieldListFilter class for a given field.
  110. field, field_list_filter_class = list_filter
  111. else:
  112. # This is simply a field name, so use the default
  113. # FieldListFilter class that has been registered for the
  114. # type of the given field.
  115. field, field_list_filter_class = list_filter, FieldListFilter.create
  116. if not isinstance(field, models.Field):
  117. field_path = field
  118. field = get_fields_from_path(self.model, field_path)[-1]
  119. lookup_params_count = len(lookup_params)
  120. spec = field_list_filter_class(
  121. field, request, lookup_params,
  122. self.model, self.model_admin, field_path=field_path,
  123. )
  124. # field_list_filter_class removes any lookup_params it
  125. # processes. If that happened, check if distinct() is needed to
  126. # remove duplicate results.
  127. if lookup_params_count > len(lookup_params):
  128. use_distinct = use_distinct or lookup_needs_distinct(self.lookup_opts, field_path)
  129. if spec and spec.has_output():
  130. filter_specs.append(spec)
  131. if self.date_hierarchy:
  132. # Create bounded lookup parameters so that the query is more
  133. # efficient.
  134. year = lookup_params.pop('%s__year' % self.date_hierarchy, None)
  135. if year is not None:
  136. month = lookup_params.pop('%s__month' % self.date_hierarchy, None)
  137. day = lookup_params.pop('%s__day' % self.date_hierarchy, None)
  138. try:
  139. from_date = datetime(
  140. int(year),
  141. int(month if month is not None else 1),
  142. int(day if day is not None else 1),
  143. )
  144. except ValueError as e:
  145. raise IncorrectLookupParameters(e) from e
  146. if settings.USE_TZ:
  147. from_date = make_aware(from_date)
  148. if day:
  149. to_date = from_date + timedelta(days=1)
  150. elif month:
  151. # In this branch, from_date will always be the first of a
  152. # month, so advancing 32 days gives the next month.
  153. to_date = (from_date + timedelta(days=32)).replace(day=1)
  154. else:
  155. to_date = from_date.replace(year=from_date.year + 1)
  156. lookup_params.update({
  157. '%s__gte' % self.date_hierarchy: from_date,
  158. '%s__lt' % self.date_hierarchy: to_date,
  159. })
  160. # At this point, all the parameters used by the various ListFilters
  161. # have been removed from lookup_params, which now only contains other
  162. # parameters passed via the query string. We now loop through the
  163. # remaining parameters both to ensure that all the parameters are valid
  164. # fields and to determine if at least one of them needs distinct(). If
  165. # the lookup parameters aren't real fields, then bail out.
  166. try:
  167. for key, value in lookup_params.items():
  168. lookup_params[key] = prepare_lookup_value(key, value)
  169. use_distinct = use_distinct or lookup_needs_distinct(self.lookup_opts, key)
  170. return filter_specs, bool(filter_specs), lookup_params, use_distinct
  171. except FieldDoesNotExist as e:
  172. raise IncorrectLookupParameters(e) from e
  173. def get_query_string(self, new_params=None, remove=None):
  174. if new_params is None:
  175. new_params = {}
  176. if remove is None:
  177. remove = []
  178. p = self.params.copy()
  179. for r in remove:
  180. for k in list(p):
  181. if k.startswith(r):
  182. del p[k]
  183. for k, v in new_params.items():
  184. if v is None:
  185. if k in p:
  186. del p[k]
  187. else:
  188. p[k] = v
  189. return '?%s' % urlencode(sorted(p.items()))
  190. def get_results(self, request):
  191. paginator = self.model_admin.get_paginator(request, self.queryset, self.list_per_page)
  192. # Get the number of objects, with admin filters applied.
  193. result_count = paginator.count
  194. # Get the total number of objects, with no admin filters applied.
  195. if self.model_admin.show_full_result_count:
  196. full_result_count = self.root_queryset.count()
  197. else:
  198. full_result_count = None
  199. can_show_all = result_count <= self.list_max_show_all
  200. multi_page = result_count > self.list_per_page
  201. # Get the list of objects to display on this page.
  202. if (self.show_all and can_show_all) or not multi_page:
  203. result_list = self.queryset._clone()
  204. else:
  205. try:
  206. result_list = paginator.page(self.page_num + 1).object_list
  207. except InvalidPage:
  208. raise IncorrectLookupParameters
  209. self.result_count = result_count
  210. self.show_full_result_count = self.model_admin.show_full_result_count
  211. # Admin actions are shown if there is at least one entry
  212. # or if entries are not counted because show_full_result_count is disabled
  213. self.show_admin_actions = not self.show_full_result_count or bool(full_result_count)
  214. self.full_result_count = full_result_count
  215. self.result_list = result_list
  216. self.can_show_all = can_show_all
  217. self.multi_page = multi_page
  218. self.paginator = paginator
  219. def _get_default_ordering(self):
  220. ordering = []
  221. if self.model_admin.ordering:
  222. ordering = self.model_admin.ordering
  223. elif self.lookup_opts.ordering:
  224. ordering = self.lookup_opts.ordering
  225. return ordering
  226. def get_ordering_field(self, field_name):
  227. """
  228. Return the proper model field name corresponding to the given
  229. field_name to use for ordering. field_name may either be the name of a
  230. proper model field or the name of a method (on the admin or model) or a
  231. callable with the 'admin_order_field' attribute. Return None if no
  232. proper model field name can be matched.
  233. """
  234. try:
  235. field = self.lookup_opts.get_field(field_name)
  236. return field.name
  237. except FieldDoesNotExist:
  238. # See whether field_name is a name of a non-field
  239. # that allows sorting.
  240. if callable(field_name):
  241. attr = field_name
  242. elif hasattr(self.model_admin, field_name):
  243. attr = getattr(self.model_admin, field_name)
  244. else:
  245. attr = getattr(self.model, field_name)
  246. return getattr(attr, 'admin_order_field', None)
  247. def get_ordering(self, request, queryset):
  248. """
  249. Return the list of ordering fields for the change list.
  250. First check the get_ordering() method in model admin, then check
  251. the object's default ordering. Then, any manually-specified ordering
  252. from the query string overrides anything. Finally, a deterministic
  253. order is guaranteed by ensuring the primary key is used as the last
  254. ordering field.
  255. """
  256. params = self.params
  257. ordering = list(self.model_admin.get_ordering(request) or self._get_default_ordering())
  258. if ORDER_VAR in params:
  259. # Clear ordering and used params
  260. ordering = []
  261. order_params = params[ORDER_VAR].split('.')
  262. for p in order_params:
  263. try:
  264. none, pfx, idx = p.rpartition('-')
  265. field_name = self.list_display[int(idx)]
  266. order_field = self.get_ordering_field(field_name)
  267. if not order_field:
  268. continue # No 'admin_order_field', skip it
  269. if hasattr(order_field, 'as_sql'):
  270. # order_field is an expression.
  271. ordering.append(order_field.desc() if pfx == '-' else order_field.asc())
  272. # reverse order if order_field has already "-" as prefix
  273. elif order_field.startswith('-') and pfx == '-':
  274. ordering.append(order_field[1:])
  275. else:
  276. ordering.append(pfx + order_field)
  277. except (IndexError, ValueError):
  278. continue # Invalid ordering specified, skip it.
  279. # Add the given query's ordering fields, if any.
  280. ordering.extend(queryset.query.order_by)
  281. # Ensure that the primary key is systematically present in the list of
  282. # ordering fields so we can guarantee a deterministic order across all
  283. # database backends.
  284. pk_name = self.lookup_opts.pk.name
  285. if {'pk', '-pk', pk_name, '-' + pk_name}.isdisjoint(ordering):
  286. # The two sets do not intersect, meaning the pk isn't present. So
  287. # we add it.
  288. ordering.append('-pk')
  289. return ordering
  290. def get_ordering_field_columns(self):
  291. """
  292. Return an OrderedDict of ordering field column numbers and asc/desc.
  293. """
  294. # We must cope with more than one column having the same underlying sort
  295. # field, so we base things on column numbers.
  296. ordering = self._get_default_ordering()
  297. ordering_fields = OrderedDict()
  298. if ORDER_VAR not in self.params:
  299. # for ordering specified on ModelAdmin or model Meta, we don't know
  300. # the right column numbers absolutely, because there might be more
  301. # than one column associated with that ordering, so we guess.
  302. for field in ordering:
  303. if isinstance(field, (Combinable, OrderBy)):
  304. if not isinstance(field, OrderBy):
  305. field = field.asc()
  306. if isinstance(field.expression, F):
  307. order_type = 'desc' if field.descending else 'asc'
  308. field = field.expression.name
  309. else:
  310. continue
  311. elif field.startswith('-'):
  312. field = field[1:]
  313. order_type = 'desc'
  314. else:
  315. order_type = 'asc'
  316. for index, attr in enumerate(self.list_display):
  317. if self.get_ordering_field(attr) == field:
  318. ordering_fields[index] = order_type
  319. break
  320. else:
  321. for p in self.params[ORDER_VAR].split('.'):
  322. none, pfx, idx = p.rpartition('-')
  323. try:
  324. idx = int(idx)
  325. except ValueError:
  326. continue # skip it
  327. ordering_fields[idx] = 'desc' if pfx == '-' else 'asc'
  328. return ordering_fields
  329. def get_queryset(self, request):
  330. # First, we collect all the declared list filters.
  331. (self.filter_specs, self.has_filters, remaining_lookup_params,
  332. filters_use_distinct) = self.get_filters(request)
  333. # Then, we let every list filter modify the queryset to its liking.
  334. qs = self.root_queryset
  335. for filter_spec in self.filter_specs:
  336. new_qs = filter_spec.queryset(request, qs)
  337. if new_qs is not None:
  338. qs = new_qs
  339. try:
  340. # Finally, we apply the remaining lookup parameters from the query
  341. # string (i.e. those that haven't already been processed by the
  342. # filters).
  343. qs = qs.filter(**remaining_lookup_params)
  344. except (SuspiciousOperation, ImproperlyConfigured):
  345. # Allow certain types of errors to be re-raised as-is so that the
  346. # caller can treat them in a special way.
  347. raise
  348. except Exception as e:
  349. # Every other error is caught with a naked except, because we don't
  350. # have any other way of validating lookup parameters. They might be
  351. # invalid if the keyword arguments are incorrect, or if the values
  352. # are not in the correct type, so we might get FieldError,
  353. # ValueError, ValidationError, or ?.
  354. raise IncorrectLookupParameters(e)
  355. if not qs.query.select_related:
  356. qs = self.apply_select_related(qs)
  357. # Set ordering.
  358. ordering = self.get_ordering(request, qs)
  359. qs = qs.order_by(*ordering)
  360. # Apply search results
  361. qs, search_use_distinct = self.model_admin.get_search_results(request, qs, self.query)
  362. # Remove duplicates from results, if necessary
  363. if filters_use_distinct | search_use_distinct:
  364. return qs.distinct()
  365. else:
  366. return qs
  367. def apply_select_related(self, qs):
  368. if self.list_select_related is True:
  369. return qs.select_related()
  370. if self.list_select_related is False:
  371. if self.has_related_field_in_list_display():
  372. return qs.select_related()
  373. if self.list_select_related:
  374. return qs.select_related(*self.list_select_related)
  375. return qs
  376. def has_related_field_in_list_display(self):
  377. for field_name in self.list_display:
  378. try:
  379. field = self.lookup_opts.get_field(field_name)
  380. except FieldDoesNotExist:
  381. pass
  382. else:
  383. if isinstance(field.remote_field, models.ManyToOneRel):
  384. # <FK>_id field names don't require a join.
  385. if field_name != field.get_attname():
  386. return True
  387. return False
  388. def url_for_result(self, result):
  389. pk = getattr(result, self.pk_attname)
  390. return reverse('admin:%s_%s_change' % (self.opts.app_label,
  391. self.opts.model_name),
  392. args=(quote(pk),),
  393. current_app=self.model_admin.admin_site.name)