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.

admin_list.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import datetime
  2. from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
  3. from django.contrib.admin.utils import (
  4. display_for_field, display_for_value, label_for_field, lookup_field,
  5. )
  6. from django.contrib.admin.views.main import (
  7. ALL_VAR, ORDER_VAR, PAGE_VAR, SEARCH_VAR,
  8. )
  9. from django.core.exceptions import ObjectDoesNotExist
  10. from django.db import models
  11. from django.template import Library
  12. from django.template.loader import get_template
  13. from django.templatetags.static import static
  14. from django.urls import NoReverseMatch
  15. from django.utils import formats
  16. from django.utils.html import format_html
  17. from django.utils.safestring import mark_safe
  18. from django.utils.text import capfirst
  19. from django.utils.translation import gettext as _
  20. from .base import InclusionAdminNode
  21. register = Library()
  22. DOT = '.'
  23. @register.simple_tag
  24. def paginator_number(cl, i):
  25. """
  26. Generate an individual page index link in a paginated list.
  27. """
  28. if i == DOT:
  29. return '… '
  30. elif i == cl.page_num:
  31. return format_html('<span class="this-page">{}</span> ', i + 1)
  32. else:
  33. return format_html(
  34. '<a href="{}"{}>{}</a> ',
  35. cl.get_query_string({PAGE_VAR: i}),
  36. mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''),
  37. i + 1,
  38. )
  39. def pagination(cl):
  40. """
  41. Generate the series of links to the pages in a paginated list.
  42. """
  43. paginator, page_num = cl.paginator, cl.page_num
  44. pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
  45. if not pagination_required:
  46. page_range = []
  47. else:
  48. ON_EACH_SIDE = 3
  49. ON_ENDS = 2
  50. # If there are 10 or fewer pages, display links to every page.
  51. # Otherwise, do some fancy
  52. if paginator.num_pages <= 10:
  53. page_range = range(paginator.num_pages)
  54. else:
  55. # Insert "smart" pagination links, so that there are always ON_ENDS
  56. # links at either end of the list of pages, and there are always
  57. # ON_EACH_SIDE links at either end of the "current page" link.
  58. page_range = []
  59. if page_num > (ON_EACH_SIDE + ON_ENDS):
  60. page_range += [
  61. *range(0, ON_ENDS), DOT,
  62. *range(page_num - ON_EACH_SIDE, page_num + 1),
  63. ]
  64. else:
  65. page_range.extend(range(0, page_num + 1))
  66. if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
  67. page_range += [
  68. *range(page_num + 1, page_num + ON_EACH_SIDE + 1), DOT,
  69. *range(paginator.num_pages - ON_ENDS, paginator.num_pages)
  70. ]
  71. else:
  72. page_range.extend(range(page_num + 1, paginator.num_pages))
  73. need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
  74. return {
  75. 'cl': cl,
  76. 'pagination_required': pagination_required,
  77. 'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
  78. 'page_range': page_range,
  79. 'ALL_VAR': ALL_VAR,
  80. '1': 1,
  81. }
  82. @register.tag(name='pagination')
  83. def pagination_tag(parser, token):
  84. return InclusionAdminNode(
  85. parser, token,
  86. func=pagination,
  87. template_name='pagination.html',
  88. takes_context=False,
  89. )
  90. def result_headers(cl):
  91. """
  92. Generate the list column headers.
  93. """
  94. ordering_field_columns = cl.get_ordering_field_columns()
  95. for i, field_name in enumerate(cl.list_display):
  96. text, attr = label_for_field(
  97. field_name, cl.model,
  98. model_admin=cl.model_admin,
  99. return_attr=True
  100. )
  101. is_field_sortable = cl.sortable_by is None or field_name in cl.sortable_by
  102. if attr:
  103. field_name = _coerce_field_name(field_name, i)
  104. # Potentially not sortable
  105. # if the field is the action checkbox: no sorting and special class
  106. if field_name == 'action_checkbox':
  107. yield {
  108. "text": text,
  109. "class_attrib": mark_safe(' class="action-checkbox-column"'),
  110. "sortable": False,
  111. }
  112. continue
  113. admin_order_field = getattr(attr, "admin_order_field", None)
  114. if not admin_order_field:
  115. is_field_sortable = False
  116. if not is_field_sortable:
  117. # Not sortable
  118. yield {
  119. 'text': text,
  120. 'class_attrib': format_html(' class="column-{}"', field_name),
  121. 'sortable': False,
  122. }
  123. continue
  124. # OK, it is sortable if we got this far
  125. th_classes = ['sortable', 'column-{}'.format(field_name)]
  126. order_type = ''
  127. new_order_type = 'asc'
  128. sort_priority = 0
  129. # Is it currently being sorted on?
  130. is_sorted = i in ordering_field_columns
  131. if is_sorted:
  132. order_type = ordering_field_columns.get(i).lower()
  133. sort_priority = list(ordering_field_columns).index(i) + 1
  134. th_classes.append('sorted %sending' % order_type)
  135. new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]
  136. # build new ordering param
  137. o_list_primary = [] # URL for making this field the primary sort
  138. o_list_remove = [] # URL for removing this field from sort
  139. o_list_toggle = [] # URL for toggling order type for this field
  140. def make_qs_param(t, n):
  141. return ('-' if t == 'desc' else '') + str(n)
  142. for j, ot in ordering_field_columns.items():
  143. if j == i: # Same column
  144. param = make_qs_param(new_order_type, j)
  145. # We want clicking on this header to bring the ordering to the
  146. # front
  147. o_list_primary.insert(0, param)
  148. o_list_toggle.append(param)
  149. # o_list_remove - omit
  150. else:
  151. param = make_qs_param(ot, j)
  152. o_list_primary.append(param)
  153. o_list_toggle.append(param)
  154. o_list_remove.append(param)
  155. if i not in ordering_field_columns:
  156. o_list_primary.insert(0, make_qs_param(new_order_type, i))
  157. yield {
  158. "text": text,
  159. "sortable": True,
  160. "sorted": is_sorted,
  161. "ascending": order_type == "asc",
  162. "sort_priority": sort_priority,
  163. "url_primary": cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}),
  164. "url_remove": cl.get_query_string({ORDER_VAR: '.'.join(o_list_remove)}),
  165. "url_toggle": cl.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}),
  166. "class_attrib": format_html(' class="{}"', ' '.join(th_classes)) if th_classes else '',
  167. }
  168. def _boolean_icon(field_val):
  169. icon_url = static('admin/img/icon-%s.svg' % {True: 'yes', False: 'no', None: 'unknown'}[field_val])
  170. return format_html('<img src="{}" alt="{}">', icon_url, field_val)
  171. def _coerce_field_name(field_name, field_index):
  172. """
  173. Coerce a field_name (which may be a callable) to a string.
  174. """
  175. if callable(field_name):
  176. if field_name.__name__ == '<lambda>':
  177. return 'lambda' + str(field_index)
  178. else:
  179. return field_name.__name__
  180. return field_name
  181. def items_for_result(cl, result, form):
  182. """
  183. Generate the actual list of data.
  184. """
  185. def link_in_col(is_first, field_name, cl):
  186. if cl.list_display_links is None:
  187. return False
  188. if is_first and not cl.list_display_links:
  189. return True
  190. return field_name in cl.list_display_links
  191. first = True
  192. pk = cl.lookup_opts.pk.attname
  193. for field_index, field_name in enumerate(cl.list_display):
  194. empty_value_display = cl.model_admin.get_empty_value_display()
  195. row_classes = ['field-%s' % _coerce_field_name(field_name, field_index)]
  196. try:
  197. f, attr, value = lookup_field(field_name, result, cl.model_admin)
  198. except ObjectDoesNotExist:
  199. result_repr = empty_value_display
  200. else:
  201. empty_value_display = getattr(attr, 'empty_value_display', empty_value_display)
  202. if f is None or f.auto_created:
  203. if field_name == 'action_checkbox':
  204. row_classes = ['action-checkbox']
  205. boolean = getattr(attr, 'boolean', False)
  206. result_repr = display_for_value(value, empty_value_display, boolean)
  207. if isinstance(value, (datetime.date, datetime.time)):
  208. row_classes.append('nowrap')
  209. else:
  210. if isinstance(f.remote_field, models.ManyToOneRel):
  211. field_val = getattr(result, f.name)
  212. if field_val is None:
  213. result_repr = empty_value_display
  214. else:
  215. result_repr = field_val
  216. else:
  217. result_repr = display_for_field(value, f, empty_value_display)
  218. if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):
  219. row_classes.append('nowrap')
  220. if str(result_repr) == '':
  221. result_repr = mark_safe('&nbsp;')
  222. row_class = mark_safe(' class="%s"' % ' '.join(row_classes))
  223. # If list_display_links not defined, add the link tag to the first field
  224. if link_in_col(first, field_name, cl):
  225. table_tag = 'th' if first else 'td'
  226. first = False
  227. # Display link to the result's change_view if the url exists, else
  228. # display just the result's representation.
  229. try:
  230. url = cl.url_for_result(result)
  231. except NoReverseMatch:
  232. link_or_text = result_repr
  233. else:
  234. url = add_preserved_filters({'preserved_filters': cl.preserved_filters, 'opts': cl.opts}, url)
  235. # Convert the pk to something that can be used in Javascript.
  236. # Problem cases are non-ASCII strings.
  237. if cl.to_field:
  238. attr = str(cl.to_field)
  239. else:
  240. attr = pk
  241. value = result.serializable_value(attr)
  242. link_or_text = format_html(
  243. '<a href="{}"{}>{}</a>',
  244. url,
  245. format_html(
  246. ' data-popup-opener="{}"', value
  247. ) if cl.is_popup else '',
  248. result_repr)
  249. yield format_html('<{}{}>{}</{}>', table_tag, row_class, link_or_text, table_tag)
  250. else:
  251. # By default the fields come from ModelAdmin.list_editable, but if we pull
  252. # the fields out of the form instead of list_editable custom admins
  253. # can provide fields on a per request basis
  254. if (form and field_name in form.fields and not (
  255. field_name == cl.model._meta.pk.name and
  256. form[cl.model._meta.pk.name].is_hidden)):
  257. bf = form[field_name]
  258. result_repr = mark_safe(str(bf.errors) + str(bf))
  259. yield format_html('<td{}>{}</td>', row_class, result_repr)
  260. if form and not form[cl.model._meta.pk.name].is_hidden:
  261. yield format_html('<td>{}</td>', form[cl.model._meta.pk.name])
  262. class ResultList(list):
  263. """
  264. Wrapper class used to return items in a list_editable changelist, annotated
  265. with the form object for error reporting purposes. Needed to maintain
  266. backwards compatibility with existing admin templates.
  267. """
  268. def __init__(self, form, *items):
  269. self.form = form
  270. super().__init__(*items)
  271. def results(cl):
  272. if cl.formset:
  273. for res, form in zip(cl.result_list, cl.formset.forms):
  274. yield ResultList(form, items_for_result(cl, res, form))
  275. else:
  276. for res in cl.result_list:
  277. yield ResultList(None, items_for_result(cl, res, None))
  278. def result_hidden_fields(cl):
  279. if cl.formset:
  280. for res, form in zip(cl.result_list, cl.formset.forms):
  281. if form[cl.model._meta.pk.name].is_hidden:
  282. yield mark_safe(form[cl.model._meta.pk.name])
  283. def result_list(cl):
  284. """
  285. Display the headers and data list together.
  286. """
  287. headers = list(result_headers(cl))
  288. num_sorted_fields = 0
  289. for h in headers:
  290. if h['sortable'] and h['sorted']:
  291. num_sorted_fields += 1
  292. return {
  293. 'cl': cl,
  294. 'result_hidden_fields': list(result_hidden_fields(cl)),
  295. 'result_headers': headers,
  296. 'num_sorted_fields': num_sorted_fields,
  297. 'results': list(results(cl)),
  298. }
  299. @register.tag(name='result_list')
  300. def result_list_tag(parser, token):
  301. return InclusionAdminNode(
  302. parser, token,
  303. func=result_list,
  304. template_name='change_list_results.html',
  305. takes_context=False,
  306. )
  307. def date_hierarchy(cl):
  308. """
  309. Display the date hierarchy for date drill-down functionality.
  310. """
  311. if cl.date_hierarchy:
  312. field_name = cl.date_hierarchy
  313. year_field = '%s__year' % field_name
  314. month_field = '%s__month' % field_name
  315. day_field = '%s__day' % field_name
  316. field_generic = '%s__' % field_name
  317. year_lookup = cl.params.get(year_field)
  318. month_lookup = cl.params.get(month_field)
  319. day_lookup = cl.params.get(day_field)
  320. def link(filters):
  321. return cl.get_query_string(filters, [field_generic])
  322. if not (year_lookup or month_lookup or day_lookup):
  323. # select appropriate start level
  324. date_range = cl.queryset.aggregate(first=models.Min(field_name),
  325. last=models.Max(field_name))
  326. if date_range['first'] and date_range['last']:
  327. if date_range['first'].year == date_range['last'].year:
  328. year_lookup = date_range['first'].year
  329. if date_range['first'].month == date_range['last'].month:
  330. month_lookup = date_range['first'].month
  331. if year_lookup and month_lookup and day_lookup:
  332. day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup))
  333. return {
  334. 'show': True,
  335. 'back': {
  336. 'link': link({year_field: year_lookup, month_field: month_lookup}),
  337. 'title': capfirst(formats.date_format(day, 'YEAR_MONTH_FORMAT'))
  338. },
  339. 'choices': [{'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))}]
  340. }
  341. elif year_lookup and month_lookup:
  342. days = getattr(cl.queryset, 'dates')(field_name, 'day')
  343. return {
  344. 'show': True,
  345. 'back': {
  346. 'link': link({year_field: year_lookup}),
  347. 'title': str(year_lookup)
  348. },
  349. 'choices': [{
  350. 'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}),
  351. 'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))
  352. } for day in days]
  353. }
  354. elif year_lookup:
  355. months = getattr(cl.queryset, 'dates')(field_name, 'month')
  356. return {
  357. 'show': True,
  358. 'back': {
  359. 'link': link({}),
  360. 'title': _('All dates')
  361. },
  362. 'choices': [{
  363. 'link': link({year_field: year_lookup, month_field: month.month}),
  364. 'title': capfirst(formats.date_format(month, 'YEAR_MONTH_FORMAT'))
  365. } for month in months]
  366. }
  367. else:
  368. years = getattr(cl.queryset, 'dates')(field_name, 'year')
  369. return {
  370. 'show': True,
  371. 'back': None,
  372. 'choices': [{
  373. 'link': link({year_field: str(year.year)}),
  374. 'title': str(year.year),
  375. } for year in years]
  376. }
  377. @register.tag(name='date_hierarchy')
  378. def date_hierarchy_tag(parser, token):
  379. return InclusionAdminNode(
  380. parser, token,
  381. func=date_hierarchy,
  382. template_name='date_hierarchy.html',
  383. takes_context=False,
  384. )
  385. def search_form(cl):
  386. """
  387. Display a search form for searching the list.
  388. """
  389. return {
  390. 'cl': cl,
  391. 'show_result_count': cl.result_count != cl.full_result_count,
  392. 'search_var': SEARCH_VAR
  393. }
  394. @register.tag(name='search_form')
  395. def search_form_tag(parser, token):
  396. return InclusionAdminNode(parser, token, func=search_form, template_name='search_form.html', takes_context=False)
  397. @register.simple_tag
  398. def admin_list_filter(cl, spec):
  399. tpl = get_template(spec.template)
  400. return tpl.render({
  401. 'title': spec.title,
  402. 'choices': list(spec.choices(cl)),
  403. 'spec': spec,
  404. })
  405. def admin_actions(context):
  406. """
  407. Track the number of times the action field has been rendered on the page,
  408. so we know which value to use.
  409. """
  410. context['action_index'] = context.get('action_index', -1) + 1
  411. return context
  412. @register.tag(name='admin_actions')
  413. def admin_actions_tag(parser, token):
  414. return InclusionAdminNode(parser, token, func=admin_actions, template_name='actions.html')
  415. @register.tag(name='change_list_object_tools')
  416. def change_list_object_tools_tag(parser, token):
  417. """Display the row of change list object tools."""
  418. return InclusionAdminNode(
  419. parser, token,
  420. func=lambda context: context,
  421. template_name='change_list_object_tools.html',
  422. )