class SKUForm(forms.ModelForm): attributes = pg_forms.HStoreField(required=False, widget=forms.HiddenInput()) class Meta: model = models.StockKeepingUnit fields = ( 'initial_quantity', 'prices', '_active', 'attributes', ) def clean(self): attrs = { field: self.cleaned_data.get(field, '') for field in self.cleaned_data['product'].attributes } self.cleaned_data['attributes'] = json.dumps(attrs) return self.cleaned_data def __init__(self, *args, **kwargs): instance = kwargs.get('instance') if instance: kwargs.setdefault('initial', {}) for attr, value in instance.attributes.items(): kwargs['initial'][attr] = value super().__init__(*args, **kwargs)
class HStoreFormTest(Form): f1 = forms.HStoreField()
def test_empty(self): field = forms.HStoreField(required=False) value = field.clean('') self.assertEqual(value, {})
def test_none_value(self): field = forms.HStoreField() value = field.clean('{"a": null}') self.assertEqual(value, {'a': None})
def test_not_string_values(self): field = forms.HStoreField() value = field.clean('{"a": 1}') self.assertEqual(value, {'a': '1'})
def test_non_dict_json(self): field = forms.HStoreField() msg = 'Input must be a JSON dictionary.' with self.assertRaisesMessage(exceptions.ValidationError, msg) as cm: field.clean('["a", "b", 1]') self.assertEqual(cm.exception.code, 'invalid_format')
def test_invalid_json(self): field = forms.HStoreField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean('{"a": "b"') self.assertEqual(cm.exception.messages[0], 'Could not load JSON data.') self.assertEqual(cm.exception.code, 'invalid_json')
def test_valid(self): field = forms.HStoreField() value = field.clean('{"a": "b"}') self.assertEqual(value, {'a': 'b'})