utils.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from django.db.models import Q
  2. from django.utils.deconstruct import deconstructible
  3. from taggit.managers import _TaggableManager
  4. from extras.constants import EXTRAS_FEATURES
  5. from extras.registry import registry
  6. def is_taggable(obj):
  7. """
  8. Return True if the instance can have Tags assigned to it; False otherwise.
  9. """
  10. if hasattr(obj, 'tags'):
  11. if issubclass(obj.tags.__class__, _TaggableManager):
  12. return True
  13. return False
  14. def image_upload(instance, filename):
  15. """
  16. Return a path for uploading image attchments.
  17. """
  18. path = 'image-attachments/'
  19. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  20. extension = filename.rsplit('.')[-1].lower()
  21. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  22. filename = '.'.join([instance.name, extension])
  23. elif instance.name:
  24. filename = instance.name
  25. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  26. @deconstructible
  27. class FeatureQuery:
  28. """
  29. Helper class that delays evaluation of the registry contents for the functionality store
  30. until it has been populated.
  31. """
  32. def __init__(self, feature):
  33. self.feature = feature
  34. def __call__(self):
  35. return self.get_query()
  36. def get_query(self):
  37. """
  38. Given an extras feature, return a Q object for content type lookup
  39. """
  40. query = Q()
  41. for app_label, models in registry['model_features'][self.feature].items():
  42. query |= Q(app_label=app_label, model__in=models)
  43. return query
  44. def register_features(model, features):
  45. for feature in features:
  46. if feature not in EXTRAS_FEATURES:
  47. raise ValueError(f"{feature} is not a valid extras feature!")
  48. app_label, model_name = model._meta.label_lower.split('.')
  49. registry['model_features'][feature][app_label].add(model_name)