utils.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from django.db.models import Q
  2. from django.utils.deconstruct import deconstructible
  3. from taggit.managers import _TaggableManager
  4. from netbox.registry import registry
  5. def is_taggable(obj):
  6. """
  7. Return True if the instance can have Tags assigned to it; False otherwise.
  8. """
  9. if hasattr(obj, 'tags'):
  10. if issubclass(obj.tags.__class__, _TaggableManager):
  11. return True
  12. return False
  13. def image_upload(instance, filename):
  14. """
  15. Return a path for uploading image attachments.
  16. """
  17. path = 'image-attachments/'
  18. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  19. extension = filename.rsplit('.')[-1].lower()
  20. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  21. filename = '.'.join([instance.name, extension])
  22. elif instance.name:
  23. filename = instance.name
  24. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  25. @deconstructible
  26. class FeatureQuery:
  27. """
  28. Helper class that delays evaluation of the registry contents for the functionality store
  29. until it has been populated.
  30. """
  31. def __init__(self, feature):
  32. self.feature = feature
  33. def __call__(self):
  34. return self.get_query()
  35. def get_query(self):
  36. """
  37. Given an extras feature, return a Q object for content type lookup
  38. """
  39. query = Q()
  40. for app_label, models in registry['model_features'][self.feature].items():
  41. query |= Q(app_label=app_label, model__in=models)
  42. return query
  43. def register_features(model, features):
  44. """
  45. Register model features in the application registry.
  46. """
  47. app_label, model_name = model._meta.label_lower.split('.')
  48. for feature in features:
  49. try:
  50. registry['model_features'][feature][app_label].add(model_name)
  51. except KeyError:
  52. raise KeyError(
  53. f"{feature} is not a valid model feature! Valid keys are: {registry['model_features'].keys()}"
  54. )
  55. def is_script(obj):
  56. """
  57. Returns True if the object is a Script.
  58. """
  59. from .scripts import Script
  60. try:
  61. return issubclass(obj, Script) and obj != Script
  62. except TypeError:
  63. return False
  64. def is_report(obj):
  65. """
  66. Returns True if the given object is a Report.
  67. """
  68. from .reports import Report
  69. try:
  70. return issubclass(obj, Report) and obj != Report
  71. except TypeError:
  72. return False