breadcrumbs.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from django.urls import get_script_prefix, resolve
  2. def get_breadcrumbs(url, request=None):
  3. """
  4. Given a url returns a list of breadcrumbs, which are each a
  5. tuple of (name, url).
  6. """
  7. from rest_framework.reverse import preserve_builtin_query_params
  8. from rest_framework.views import APIView
  9. def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen):
  10. """
  11. Add tuples of (name, url) to the breadcrumbs list,
  12. progressively chomping off parts of the url.
  13. """
  14. try:
  15. (view, unused_args, unused_kwargs) = resolve(url)
  16. except Exception:
  17. pass
  18. else:
  19. # Check if this is a REST framework view,
  20. # and if so add it to the breadcrumbs
  21. cls = getattr(view, 'cls', None)
  22. initkwargs = getattr(view, 'initkwargs', {})
  23. if cls is not None and issubclass(cls, APIView):
  24. # Don't list the same view twice in a row.
  25. # Probably an optional trailing slash.
  26. if not seen or seen[-1] != view:
  27. c = cls(**initkwargs)
  28. name = c.get_view_name()
  29. insert_url = preserve_builtin_query_params(prefix + url, request)
  30. breadcrumbs_list.insert(0, (name, insert_url))
  31. seen.append(view)
  32. if url == '':
  33. # All done
  34. return breadcrumbs_list
  35. elif url.endswith('/'):
  36. # Drop trailing slash off the end and continue to try to
  37. # resolve more breadcrumbs
  38. url = url.rstrip('/')
  39. return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen)
  40. # Drop trailing non-slash off the end and continue to try to
  41. # resolve more breadcrumbs
  42. url = url[:url.rfind('/') + 1]
  43. return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen)
  44. prefix = get_script_prefix().rstrip('/')
  45. url = url[len(prefix):]
  46. return breadcrumbs_recursive(url, [], prefix, [])