diff --git a/SAS/TMSS/src/tmss/tmssapp/serializers/widgets.py b/SAS/TMSS/src/tmss/tmssapp/serializers/widgets.py index 7aaf8970a0c4b734cc9fcd32137ebb97755cb45b..d2d3adfff7c5bd8b6e3ea87cc717997bd1db4f04 100644 --- a/SAS/TMSS/src/tmss/tmssapp/serializers/widgets.py +++ b/SAS/TMSS/src/tmss/tmssapp/serializers/widgets.py @@ -14,20 +14,29 @@ class JSONEditorField(serializers.JSONField): """ An enhanced JSONField that provides a nice editor widget with validation against the $schema in the json field value. """ - def __init__(self, schema_source: str=None, *args, **kwargs): + '''schema_source should be a string 'pointing to' the used template and it's schema property. + For example in the SubtaskSerializer, we point to the specifications_template's schema like so: + specifications_doc = JSONEditorField(schema_source='specifications_template.schema') + ''' self.schema_source = schema_source super().__init__(*args, **kwargs) def get_schema(self, json_data=None): + '''get the schema that this JSONEditorField is using via the schema_source''' try: - serializer = self.parent - return fields.get_attribute(serializer.instance, self.schema_source.split('.')) + if isinstance(self.parent.instance, list): + # the serializer is serializing a list of model instances, so we cannot get a single schema from a single instance + return None + return fields.get_attribute(self.parent.instance, self.schema_source.split('.')) except (AttributeError, TypeError): try: if json_data and '$schema' in json_data: schema_url = json_data['$schema'] - return json.loads(requests.get(schema_url).text) + response = requests.get(schema_url) + if response.status_code == 200: + schema = response.text + return json.loads(schema) except (KeyError, TypeError, json.JSONDecodeError): pass return None @@ -45,7 +54,7 @@ class JSONEditorField(serializers.JSONField): def to_representation(self, value): '''create representation of the json-schema-value, - with all common json schema refs pointing to the correct host, + with all common json schema $ref's pointing to the correct host, and inject the josdejong_jsoneditor_widget.html in the render style based on the requests accepted_media_type''' self.style = {}