tables.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from django.utils.translation import gettext_lazy as _
  2. from netbox.registry import registry
  3. __all__ = (
  4. 'get_table_ordering',
  5. 'linkify_phone',
  6. 'register_table_column'
  7. )
  8. def get_table_ordering(request, table):
  9. """
  10. Given a request, return the prescribed table ordering, if any. This may be necessary to determine prior to rendering
  11. the table itself.
  12. """
  13. # Check for an explicit ordering
  14. if 'sort' in request.GET:
  15. return request.GET['sort'] or None
  16. # Check for a configured preference
  17. if request.user.is_authenticated:
  18. if preference := request.user.config.get(f'tables.{table.__name__}.ordering'):
  19. return preference
  20. def linkify_phone(value):
  21. """
  22. Render a telephone number as a hyperlink.
  23. """
  24. if value is None:
  25. return None
  26. return f"tel:{value.replace(' ', '')}"
  27. def register_table_column(column, name, *tables):
  28. """
  29. Register a custom column for use on one or more tables.
  30. Args:
  31. column: The column instance to register
  32. name: The name of the table column
  33. tables: One or more table classes
  34. """
  35. for table in tables:
  36. reg = registry['tables'][table]
  37. if name in reg:
  38. raise ValueError(_("A column named {name} is already defined for table {table_name}").format(
  39. name=name, table_name=table.__name__
  40. ))
  41. reg[name] = column