示例#1
0
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)
示例#2
0
 class HStoreFormTest(Form):
     f1 = forms.HStoreField()
示例#3
0
 def test_empty(self):
     field = forms.HStoreField(required=False)
     value = field.clean('')
     self.assertEqual(value, {})
示例#4
0
 def test_none_value(self):
     field = forms.HStoreField()
     value = field.clean('{"a": null}')
     self.assertEqual(value, {'a': None})
示例#5
0
 def test_not_string_values(self):
     field = forms.HStoreField()
     value = field.clean('{"a": 1}')
     self.assertEqual(value, {'a': '1'})
示例#6
0
 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')
示例#7
0
 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')
示例#8
0
 def test_valid(self):
     field = forms.HStoreField()
     value = field.clean('{"a": "b"}')
     self.assertEqual(value, {'a': 'b'})