import jsonschema from jsonschema import Draft7Validator from rest_framework.exceptions import ValidationError FIELD_TYPE_TO_JSONSCHEMA = { 'text': {'type': 'string'}, 'number': {'type': ['number', 'integer']}, 'boolean': {'type': 'boolean'}, 'date': {'type': 'string', 'format': 'date'}, 'datetime': {'type': 'string', 'format': 'date-time'}, 'email': {'type': 'string', 'format': 'email'}, 'url': {'type': 'string', 'format': 'uri'}, } def build_schema_for_object(custom_object, partial=False): """ Dynamically generates JSONSchema Draft 7 representation of CustomObjectDefinition fields. """ properties = {} required = [] fields = custom_object.fields.all() for field in fields: f_type = field.field_type if f_type in FIELD_TYPE_TO_JSONSCHEMA: field_def = dict(FIELD_TYPE_TO_JSONSCHEMA[f_type]) elif f_type in ('select', 'picklist'): field_def = {'type': 'string', 'enum': field.options or field.choices or []} elif f_type == 'lookup': field_def = {'type': ['integer', 'null']} else: field_def = {} field_def['title'] = field.label properties[field.name] = field_def if field.is_required and not partial: required.append(field.name) schema = { '$schema': 'http://json-schema.org/draft-07/schema#', 'title': custom_object.label, 'type': 'object', 'properties': properties, 'additionalProperties': False, } if required: schema['required'] = required return schema def validate_record_data(custom_object, data, partial=False): """ Validates record payload against the dynamic schema """ schema = build_schema_for_object(custom_object, partial=partial) validator = Draft7Validator(schema) errors = {} for err in sorted(validator.iter_errors(data), key=lambda e: e.path): field = err.path[0] if err.path else 'non_field_errors' errors.setdefault(field, []).append(err.message) if errors: raise ValidationError(errors) return True