2
0

utils.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from taggit.managers import _TaggableManager
  2. from netbox.registry import registry
  3. def is_taggable(obj):
  4. """
  5. Return True if the instance can have Tags assigned to it; False otherwise.
  6. """
  7. if hasattr(obj, 'tags'):
  8. if issubclass(obj.tags.__class__, _TaggableManager):
  9. return True
  10. return False
  11. def image_upload(instance, filename):
  12. """
  13. Return a path for uploading image attachments.
  14. """
  15. path = 'image-attachments/'
  16. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  17. extension = filename.rsplit('.')[-1].lower()
  18. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  19. filename = '.'.join([instance.name, extension])
  20. elif instance.name:
  21. filename = instance.name
  22. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  23. def register_features(model, features):
  24. """
  25. Register model features in the application registry.
  26. """
  27. app_label, model_name = model._meta.label_lower.split('.')
  28. for feature in features:
  29. try:
  30. registry['model_features'][feature][app_label].add(model_name)
  31. except KeyError:
  32. raise KeyError(
  33. f"{feature} is not a valid model feature! Valid keys are: {registry['model_features'].keys()}"
  34. )
  35. # Register public models
  36. if not getattr(model, '_netbox_private', False):
  37. registry['models'][app_label].add(model_name)
  38. def is_script(obj):
  39. """
  40. Returns True if the object is a Script.
  41. """
  42. from .scripts import Script
  43. try:
  44. return issubclass(obj, Script) and obj != Script
  45. except TypeError:
  46. return False
  47. def is_report(obj):
  48. """
  49. Returns True if the given object is a Report.
  50. """
  51. from .reports import Report
  52. try:
  53. return issubclass(obj, Report) and obj != Report
  54. except TypeError:
  55. return False