From 54926bad01b74c780640f166318246bb88bb4c13 Mon Sep 17 00:00:00 2001 From: Bharat Chauhan Date: Fri, 13 Sep 2024 22:00:46 +0530 Subject: [PATCH] Fix #72: Allow providing custom schema for ArrayField --- django_jsonform/forms/fields.py | 4 ++++ django_jsonform/models/fields.py | 8 +++++++- tests/models/test_fields.py | 11 ++++++++++- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/django_jsonform/forms/fields.py b/django_jsonform/forms/fields.py index 30e343c..fc9ce64 100644 --- a/django_jsonform/forms/fields.py +++ b/django_jsonform/forms/fields.py @@ -85,6 +85,7 @@ def __init__(self, base_field, **kwargs): self.min_items = kwargs.get('min_length') self.nested = kwargs.pop('nested', False) + self.schema = kwargs.pop('schema', None) if not self.nested: self.widget = JSONFormWidget(schema=self.get_schema()) @@ -107,6 +108,9 @@ def to_python(self, value): return super().to_python(value) def get_schema(self): + if self.schema: + return self.schema + schema = {'type': 'array'} if isinstance(self.base_field, ArrayFormField): diff --git a/django_jsonform/models/fields.py b/django_jsonform/models/fields.py index 8be448f..3cf1af1 100644 --- a/django_jsonform/models/fields.py +++ b/django_jsonform/models/fields.py @@ -56,7 +56,13 @@ def __init__(self, *args, **kwargs): raise ImproperlyConfigured('ArrayField requires psycopg2 to be installed.') self.nested = kwargs.pop('nested', False) + self.schema = kwargs.pop('schema', None) super().__init__(*args, **kwargs) def formfield(self, **kwargs): - return super().formfield(**{'form_class': ArrayFormField, 'nested': self.nested, **kwargs}) + return super().formfield(**{ + 'form_class': ArrayFormField, + 'nested': self.nested, + 'schema': self.schema, + **kwargs, + }) diff --git a/tests/models/test_fields.py b/tests/models/test_fields.py index 6b42bca..4621ae1 100644 --- a/tests/models/test_fields.py +++ b/tests/models/test_fields.py @@ -1,6 +1,7 @@ from unittest import TestCase from unittest.mock import MagicMock, patch -from django_jsonform.models.fields import JSONField +from django_jsonform.models.fields import JSONField, ArrayField +from django.db import models class JSONFieldTests(TestCase): @@ -11,3 +12,11 @@ def test_calls_pre_save_hook_if_provided(self): model_instance = MagicMock() field.pre_save(model_instance, True) pre_save_hook.assert_called_once() + + +class ArrayFieldTests(TestCase): + def test_allows_providing_custom_schema(self): + schema = {'type': 'array', 'items': {'type': 'string'}} + + # initialising the ArrayField with custom schema must succeed + field = ArrayField(models.CharField(max_length=10), schema=schema)