config.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from django.core.paginator import EmptyPage, PageNotAnInteger
  2. class RequestConfig:
  3. """
  4. A configurator that uses request data to setup a table.
  5. A single RequestConfig can be used for multiple tables in one view.
  6. Arguments:
  7. paginate (dict or bool): Indicates whether to paginate, and if so, what
  8. default values to use. If the value evaluates to `False`, pagination
  9. will be disabled. A `dict` can be used to specify default values for
  10. the call to `~.tables.Table.paginate` (e.g. to define a default
  11. `per_page` value).
  12. A special *silent* item can be used to enable automatic handling of
  13. pagination exceptions using the following logic:
  14. - If `~django.core.paginator.PageNotAnInteger` is raised, show the first page.
  15. - If `~django.core.paginator.EmptyPage` is raised, show the last page.
  16. For example, to use `~.LazyPaginator`::
  17. RequestConfig(paginate={"paginator_class": LazyPaginator}).configure(table)
  18. """
  19. def __init__(self, request, paginate=True):
  20. self.request = request
  21. self.paginate = paginate
  22. def configure(self, table):
  23. """
  24. Configure a table using information from the request.
  25. Arguments:
  26. table (`~.Table`): table to be configured
  27. """
  28. order_by = self.request.GET.getlist(table.prefixed_order_by_field)
  29. if order_by:
  30. table.order_by = order_by
  31. if self.paginate:
  32. if hasattr(self.paginate, "items"):
  33. kwargs = dict(self.paginate)
  34. else:
  35. kwargs = {}
  36. # extract some options from the request
  37. for arg in ("page", "per_page"):
  38. name = getattr(table, "prefixed_%s_field" % arg)
  39. try:
  40. kwargs[arg] = int(self.request.GET[name])
  41. except (ValueError, KeyError):
  42. pass
  43. silent = kwargs.pop("silent", True)
  44. if not silent:
  45. table.paginate(**kwargs)
  46. else:
  47. try:
  48. table.paginate(**kwargs)
  49. except PageNotAnInteger:
  50. table.page = table.paginator.page(1)
  51. except EmptyPage:
  52. table.page = table.paginator.page(table.paginator.num_pages)
  53. table.request = self.request
  54. return table