shortcuts.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import six
  2. from django.http import Http404
  3. from django.shortcuts import * # noqa
  4. def paginate(object_list, page, per_page, orphans=0,
  5. allow_empty_first_page=True,
  6. allow_explicit_first_page=False,
  7. paginator=None):
  8. from django.core.paginator import Paginator, EmptyPage, InvalidPage
  9. from .exceptions import ExplicitFirstPage
  10. if page in (1, "1") and not allow_explicit_first_page:
  11. raise ExplicitFirstPage()
  12. elif not page:
  13. page = 1
  14. paginator = paginator or Paginator
  15. try:
  16. return paginator(
  17. object_list, per_page, orphans=orphans,
  18. allow_empty_first_page=allow_empty_first_page).page(page)
  19. except (EmptyPage, InvalidPage) as e:
  20. raise Http404()
  21. def pagination_dict(page):
  22. pagination = {
  23. 'page': page.number,
  24. 'pages': page.paginator.num_pages,
  25. 'count': page.paginator.count,
  26. 'first': None,
  27. 'previous': None,
  28. 'next': None,
  29. 'last': None,
  30. 'before': 0,
  31. 'more': 0,
  32. }
  33. if page.has_previous():
  34. pagination['first'] = 1
  35. if page.previous_page_number() > 1:
  36. pagination['previous'] = page.previous_page_number()
  37. if page.has_next():
  38. pagination['last'] = page.paginator.num_pages
  39. if page.next_page_number() <= page.paginator.num_pages:
  40. pagination['next'] = page.next_page_number()
  41. if page.start_index():
  42. pagination['before'] = page.start_index() - 1
  43. pagination['more'] = page.paginator.count - page.end_index()
  44. return pagination
  45. def validate_slug(model, slug):
  46. from .exceptions import OutdatedSlug
  47. if model.slug != slug:
  48. raise OutdatedSlug(model)
  49. def get_int_or_404(value):
  50. if six.text_type(value).isdigit():
  51. return int(value)
  52. else:
  53. raise Http404()