Skip to content

Reference

hope_flex_fields.models.FieldDefinition

This class is the equivalent django.forms.Field class, used to create reusable field types

Source code in src/hope_flex_fields/models/definition.py
 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

hope_flex_fields.models.Fieldset

hope_flex_fields.models.FlexField

Source code in src/hope_flex_fields/models/flexfield.py
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 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
class FlexField(AbstractField):
    fieldset = models.ForeignKey(Fieldset, on_delete=models.CASCADE, related_name="fields")
    definition = models.ForeignKey(FieldDefinition, on_delete=models.CASCADE, related_name="instances")
    master = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE, related_name="+")

    objects = FieldsetFieldManager()

    class Meta:
        verbose_name = _("Flex Field")
        verbose_name_plural = _("flex Fields")
        constraints = (
            UniqueConstraint(fields=("name", "fieldset"), name="flexfield_unique_name"),
            UniqueConstraint(fields=("slug", "fieldset"), name="flexfield_unique_slug"),
        )

    def __str__(self):
        return self.name

    @property
    def attributes(self):
        return self.attrs

    @attributes.setter
    def attributes(self, value):
        self.attrs = value

    @property
    def dependants(self):
        return FlexField.objects.filter(master=self)

    def base_type(self):
        return self.definition.field_type.__name__

    def validate_attrs(self):
        try:
            self.get_field()
        except Exception as e:
            raise ValidationError(e)

    def clean(self):
        self.name = namefy(str(self.name))
        self.validate_attrs()

    def natural_key(self):
        return self.name, self.fieldset.name

    def get_merged_attrs(self):
        attrs = dict(**self.definition.get_attributes(self))
        if isinstance(self.attributes, dict):
            attrs.update(self.attrs)
        return attrs

    def get_field(self, override_attrs=None, **extra) -> "FlexFormMixin":
        try:
            if override_attrs is not None:
                kwargs = dict(override_attrs)
            else:
                kwargs = self.get_merged_attrs()
                kwargs.update(extra)
            validators = []
            if self.validation:
                validators.append(JsValidator(self.validation))
            elif self.definition.validation:
                validators.append(JsValidator(self.definition.validation))

            if self.regex:
                validators.append(ReValidator(self.regex))
            elif self.definition.regex:
                validators.append(ReValidator(self.definition.regex))

            kwargs["validators"] = validators
            field_class = type(
                f"{self.name}Field",
                (FlexFormMixin, self.definition.field_type),
                {"flex_field": self},
            )
            fld = field_class(**kwargs)
            if self.definition.attributes_strategy.validators:
                fld.validators.extend([v(fld) for v in self.definition.attributes_strategy.validators])
        except Exception as e:  # pragma: no cover
            raise FlexFieldCreationError(f"Error creating field for FlexField {self.name}: {e}")
        return fld

hope_flex_fields.models.DataChecker

Used for complex validations to combine different fieldsets

Source code in src/hope_flex_fields/models/datachecker.py
 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
class DataChecker(ValidatorMixin, models.Model):
    """Used for complex validations to combine different fieldsets"""

    last_modified = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(blank=True)
    fieldsets = models.ManyToManyField(Fieldset, through=DataCheckerFieldset)
    objects = DataCheckerManager()

    class Meta:
        verbose_name = _("DataChecker")
        verbose_name_plural = _("DataCheckers")

    def __str__(self):
        return self.name

    def natural_key(self):
        return (self.name,)

    @memoized_method()
    def get_fields(self) -> Generator["FlexField", None, None]:
        fs: DataCheckerFieldset
        for fs in self.members.select_related("fieldset").all():
            # for field in fs.fieldset.fields.select_related("definition").filter():
            for field in fs.fieldset.get_fields():
                yield fs, field

    @memoized_method()
    def get_field(self, name) -> "FlexField":
        for __, field in self.get_fields():
            if field.name == name:
                return field

    # for fs in self.members.all():
    #     for field in fs.fieldset.fields.select_related("definition").filter():
    #         if field.name == name:
    #             return field
    @deprecated("0.6.3", details="uses get_form_class()")
    def get_form(self) -> "Generic[F]":
        return self.get_form_class()

    def get_form_class(self) -> "Generic[F]":
        from ..forms import FlexForm

        fields: dict[str, forms.Field] = {}
        field: "FlexField"
        # for fs in self.members.select_related("fieldset").all():
        #     for field in fs.fieldset.fields.select_related("definition").filter():
        for fs, field in self.get_fields():
            fld: FlexFormMixin = field.get_field()
            fld.label = f"{fs.prefix}{field.name}"
            if "%s" in fs.prefix:
                full_name = fs.prefix % field.name
            else:
                full_name = f"{fs.prefix}{field.name}"

            fields[full_name] = fld
        form_class_attrs = {"datachecker": self, "validator": self, **dict(sorted(fields.items()))}
        return type(f"{self.name}DataCheckerForm", (FlexForm,), form_class_attrs)