2020-03-14 03:03:22 -04:00
|
|
|
from django.db.models import Q
|
|
|
|
from django.utils.deconstruct import deconstructible
|
2019-12-11 15:26:47 -05:00
|
|
|
from taggit.managers import _TaggableManager
|
|
|
|
|
2020-03-14 03:03:22 -04:00
|
|
|
from extras.constants import EXTRAS_FEATURES
|
2020-03-18 12:00:31 -04:00
|
|
|
from extras.registry import registry
|
2020-03-14 03:03:22 -04:00
|
|
|
|
2019-12-11 15:26:47 -05:00
|
|
|
|
|
|
|
def is_taggable(obj):
|
|
|
|
"""
|
|
|
|
Return True if the instance can have Tags assigned to it; False otherwise.
|
|
|
|
"""
|
|
|
|
if hasattr(obj, 'tags'):
|
|
|
|
if issubclass(obj.tags.__class__, _TaggableManager):
|
|
|
|
return True
|
|
|
|
return False
|
2020-03-14 03:03:22 -04:00
|
|
|
|
|
|
|
|
2020-05-07 16:59:27 -04:00
|
|
|
def image_upload(instance, filename):
|
|
|
|
"""
|
|
|
|
Return a path for uploading image attchments.
|
|
|
|
"""
|
|
|
|
path = 'image-attachments/'
|
|
|
|
|
|
|
|
# Rename the file to the provided name, if any. Attempt to preserve the file extension.
|
|
|
|
extension = filename.rsplit('.')[-1].lower()
|
|
|
|
if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
|
|
|
|
filename = '.'.join([instance.name, extension])
|
|
|
|
elif instance.name:
|
|
|
|
filename = instance.name
|
|
|
|
|
|
|
|
return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
|
|
|
|
|
|
|
|
|
2020-03-14 03:03:22 -04:00
|
|
|
@deconstructible
|
2020-03-16 11:58:35 -04:00
|
|
|
class FeatureQuery:
|
2020-03-14 03:03:22 -04:00
|
|
|
"""
|
2020-03-18 12:00:31 -04:00
|
|
|
Helper class that delays evaluation of the registry contents for the functionality store
|
2020-03-14 03:03:22 -04:00
|
|
|
until it has been populated.
|
|
|
|
"""
|
|
|
|
def __init__(self, feature):
|
|
|
|
self.feature = feature
|
|
|
|
|
|
|
|
def __call__(self):
|
2020-03-16 11:58:35 -04:00
|
|
|
return self.get_query()
|
2020-03-14 03:03:22 -04:00
|
|
|
|
2020-03-16 11:58:35 -04:00
|
|
|
def get_query(self):
|
2020-03-14 03:03:22 -04:00
|
|
|
"""
|
|
|
|
Given an extras feature, return a Q object for content type lookup
|
|
|
|
"""
|
|
|
|
query = Q()
|
2020-03-18 12:00:31 -04:00
|
|
|
for app_label, models in registry['model_features'][self.feature].items():
|
2020-03-14 03:03:22 -04:00
|
|
|
query |= Q(app_label=app_label, model__in=models)
|
|
|
|
|
|
|
|
return query
|
|
|
|
|
|
|
|
|
2022-01-19 14:46:50 -05:00
|
|
|
def register_features(model, features):
|
|
|
|
for feature in features:
|
|
|
|
if feature not in EXTRAS_FEATURES:
|
|
|
|
raise ValueError(f"{feature} is not a valid extras feature!")
|
|
|
|
app_label, model_name = model._meta.label_lower.split('.')
|
2022-01-19 15:22:28 -05:00
|
|
|
registry['model_features'][feature][app_label].add(model_name)
|