52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161 | class FieldDefinition(AbstractField):
"""This class is the equivalent django.forms.Field class, used to create reusable field types"""
field_type = StrategyClassField(registry=field_registry, null=False, blank=False)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True)
system_data = models.JSONField(default=dict, blank=True, editable=False, null=True)
attributes_strategy = StrategyField(
registry=attributes_registry,
default=fqn(DefaultAttributeHandler),
help_text="Strategy to use for attributes retrieval",
)
strategy_config = models.JSONField(default=dict, blank=True, editable=False, null=True)
validated = models.BooleanField(default=False, blank=True)
objects = FieldDefinitionManager()
class Meta:
verbose_name = _("Field Definition")
verbose_name_plural = _("Field Definitions")
constraints = (
UniqueConstraint(fields=("name",), name="fielddefinition_unique_name"),
UniqueConstraint(fields=("slug",), name="fielddefinition_unique_slug"),
)
def __str__(self):
return self.name
@property
def attributes(self):
base = self.attrs
try:
return base | self.attributes_strategy.get()
except Exception:
self.validated = False
return base
@attributes.setter
def attributes(self, value):
self.attributes_strategy.set(value)
def get_attributes(self, instance: "FlexField"):
return self.attributes_strategy.get(instance)
def natural_key(self):
return (self.name,)
def clean(self):
self.name = str(self.name)
try:
self.get_field()
except TypeError:
raise ValidationError("Field definition cannot be validated")
def save(
self,
*args,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
self.attrs = self.get_default_attributes() | self.attrs
if not update_fields:
self.validated = False
elif "validated" in update_fields:
pass
super().save(
*args,
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields,
)
def get_default_attributes(self):
attrs = get_common_attrs()
if self.field_type:
return attrs | get_kwargs_from_field_class(self.field_type)
return attrs
def set_default_attributes(self):
if self.field_type:
attrs = self.get_default_attributes()
self.attributes = attrs
elif not isinstance(self.attrs, dict) or not self.attrs:
self.attributes = get_common_attrs()
@property
def required(self):
return self.attributes.get("required", False)
def get_field(self, override_attrs=None):
try:
if override_attrs is not None:
kwargs = dict(override_attrs)
else:
kwargs = dict(self.attributes)
validators = []
if self.validation:
validators.append(JsValidator(self.validation))
if self.regex:
validators.append(ReValidator(self.regex))
kwargs["validators"] = validators
field_class = type(f"{self.name}Field", (FlexFormMixin, self.field_type), {})
fld = field_class(**kwargs)
except Exception as e: # pragma: no cover
logger.exception(e)
raise TypeError(f"Error creating field for FieldDefinition {self.name}: {e}")
return fld
|