Debian Codegraph @

colorfield/fields.py

raw symbols SCIP
1 from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
2 from django.db.models import CharField, signals
3 from django.db.models.fields.files import ImageField
4
5 from colorfield.utils import get_image_file_background_color
6 from colorfield.validators import (
7 color_hex_validator,
8 color_hexa_validator,
9 color_rgb_validator,
10 color_rgba_validator,
11 )
12 from colorfield.widgets import ColorWidget
13
14 VALIDATORS_PER_FORMAT = {
15 "hex": color_hex_validator,
16 "hexa": color_hexa_validator,
17 "rgb": color_rgb_validator,
18 "rgba": color_rgba_validator,
19 }
20
21 DEFAULT_PER_FORMAT = {
22 "hex": "#FFFFFF",
23 "hexa": "#FFFFFFFF",
24 "rgb": "rgb(255, 255, 255)",
25 "rgba": "rgba(255, 255, 255, 1)",
26 }
27
28
29 class ColorField(CharField):
30 default_validators = []
31
32 def __init__(self, *args, **kwargs):
33 # works like Django choices, but does not restrict input to the given choices
34 self.samples = kwargs.pop("samples", None)
35 self.format = kwargs.pop("format", "hex").lower()
36 if self.format not in ["hex", "hexa", "rgb", "rgba"]:
37 raise ValueError(f"Unsupported color format: {self.format}")
38 self.default_validators = [VALIDATORS_PER_FORMAT[self.format]]
39
40 self.image_field = kwargs.pop("image_field", None)
41 if self.image_field:
42 kwargs.setdefault("blank", True)
43
44 kwargs.setdefault("max_length", 25)
45 if kwargs.get("null"):
46 kwargs.setdefault("blank", True)
47 kwargs.setdefault("default", None)
48 elif kwargs.get("blank"):
49 kwargs.setdefault("default", "")
50 else:
51 kwargs.setdefault("default", DEFAULT_PER_FORMAT[self.format])
52 super().__init__(*args, **kwargs)
53
54 if self.choices and self.samples:
55 raise ImproperlyConfigured(
56 "Invalid options: 'choices' and 'samples' are mutually exclusive, "
57 "you can set only one of the two for a ColorField instance."
58 )
59
60 def formfield(self, **kwargs):
61 palette = []
62 if self.choices:
63 choices = self.get_choices(include_blank=False)
64 palette = [choice[0] for choice in choices]
65 elif self.samples:
66 palette = [choice[0] for choice in self.samples]
67 kwargs["widget"] = ColorWidget(
68 attrs={
69 "default": self.get_default(),
70 "format": self.format,
71 "palette": palette,
72 # # TODO: in case choices is defined,
73 # # this will be used to hide the widget color spectrum
74 # 'palette_choices_only': bool(self.choices),
75 }
76 )
77 return super().formfield(**kwargs)
78
79 def contribute_to_class(self, cls, name, **kwargs):
80 super().contribute_to_class(cls, name, **kwargs)
81 if cls._meta.abstract:
82 return
83 if self.image_field:
84 signals.post_save.connect(self._update_from_image_field, sender=cls)
85
86 def deconstruct(self):
87 name, path, args, kwargs = super().deconstruct()
88 kwargs["samples"] = self.samples
89 kwargs["image_field"] = self.image_field
90 return name, path, args, kwargs
91
92 def _get_image_field_color(self, instance):
93 color = ""
94 image_file = getattr(instance, self.image_field)
95 if image_file:
96 with image_file.open() as _:
97 color = get_image_file_background_color(image_file, self.format)
98 return color
99
100 def _update_from_image_field(self, instance, created, *args, **kwargs):
101 if not instance or not instance.pk or not self.image_field:
102 return
103 # check if the field is a valid ImageField
104 try:
105 field_cls = instance._meta.get_field(self.image_field)
106 if not isinstance(field_cls, ImageField):
107 raise ImproperlyConfigured(
108 "Invalid 'image_field' field type, "
109 "expected an instance of 'models.ImageField'."
110 )
111 except FieldDoesNotExist as error:
112 raise ImproperlyConfigured(
113 "Invalid 'image_field' field name, "
114 f"{self.image_field!r} field not found."
115 ) from error
116 # update value from picking color from image field
117 color = self._get_image_field_color(instance)
118 color_field_name = self.attname
119 color_field_value = getattr(instance, color_field_name, None)
120 if color_field_value != color and color:
121 color_field_value = color or self.default
122 # update in-memory value
123 setattr(instance, color_field_name, color_field_value)
124 # update stored value
125 manager = instance.__class__.objects
126 manager.filter(pk=instance.pk).update(
127 **{color_field_name: color_field_value}
128 )