Python django.contrib.postgres.fields.JSONField() Examples

The following are 30 code examples of django.contrib.postgres.fields.JSONField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.postgres.fields , or try the search function .
Example #1
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_redisplay_wrong_input(self):
        """
        When displaying a bound form (typically due to invalid input), the form
        should not overquote JSONField inputs.
        """
        class JsonForm(Form):
            name = CharField(max_length=2)
            jfield = forms.JSONField()

        # JSONField input is fine, name is too long
        form = JsonForm({'name': 'xyz', 'jfield': '["foo"]'})
        self.assertIn('[&quot;foo&quot;]</textarea>', form.as_p())

        # This time, the JSONField input is wrong
        form = JsonForm({'name': 'xy', 'jfield': '{"foo"}'})
        # Appears once in the textarea and once in the error message
        self.assertEqual(form.as_p().count(escape('{"foo"}')), 2) 
Example #2
Source File: mt_models.py    From zentral with Apache License 2.0 6 votes vote down vote up
def hash(self, recursive=True):
        h = Hasher()
        for f, v in self._iter_mto_fields():
            if f.many_to_one and v:
                if recursive:
                    v = v.hash()
                else:
                    v = v.mt_hash
            elif f.many_to_many:
                if recursive:
                    v = [mto.hash() for mto in v]
                else:
                    v = [mto.mt_hash for mto in v]
            elif isinstance(f, JSONField) and v:
                t = copy.deepcopy(v)
                prepare_commit_tree(t)
                v = t['mt_hash']
            h.add_field(f.name, v)
        return h.hexdigest() 
Example #3
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_already_converted_value(self):
        field = forms.JSONField(required=False)
        tests = [
            '["a", "b", "c"]', '{"a": 1, "b": 2}', '1', '1.5', '"foo"',
            'true', 'false', 'null',
        ]
        for json_string in tests:
            val = field.clean(json_string)
            self.assertEqual(field.clean(val), val) 
Example #4
Source File: filters.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def _build_search_expression(self, field_lookup):
        # TODO: is there no Django API which allows conversion of lookup to django field?
        model_field, _ = reduce(
            lambda model_tuple, field: self._get_model_field(model_tuple[1], field),
            field_lookup.split(LOOKUP_SEP),
            (None, self.model),
        )

        if isinstance(model_field, LocalizedField):
            lang = translation.get_language()
            return KeyTransform(lang, field_lookup)
        elif isinstance(model_field, JSONField):
            return Cast(field_lookup, models.TextField())

        return field_lookup 
Example #5
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_has_changed(self):
        field = forms.JSONField()
        self.assertIs(field.has_changed({'a': True}, '{"a": 1}'), True)
        self.assertIs(field.has_changed({'a': 1, 'b': 2}, '{"b": 2, "a": 1}'), False) 
Example #6
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid_default(self):
        class MyModel(PostgreSQLModel):
            field = JSONField(default=dict)

        model = MyModel()
        self.assertEqual(model.check(), []) 
Example #7
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid_default_none(self):
        class MyModel(PostgreSQLModel):
            field = JSONField(default=None)

        model = MyModel()
        self.assertEqual(model.check(), []) 
Example #8
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_serializable(self):
        field = JSONField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(datetime.timedelta(days=1), None)
        self.assertEqual(cm.exception.code, 'invalid')
        self.assertEqual(cm.exception.message % cm.exception.params, "Value must be valid JSON.") 
Example #9
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_custom_encoder(self):
        with self.assertRaisesMessage(ValueError, "The encoder parameter must be a callable object."):
            field = JSONField(encoder=DjangoJSONEncoder())
        field = JSONField(encoder=DjangoJSONEncoder)
        self.assertEqual(field.clean(datetime.timedelta(days=1), None), datetime.timedelta(days=1)) 
Example #10
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid(self):
        field = forms.JSONField()
        value = field.clean('{"a": "b"}')
        self.assertEqual(value, {'a': 'b'}) 
Example #11
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid(self):
        field = forms.JSONField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean('{some badly formed: json}')
        self.assertEqual(cm.exception.messages[0], "'{some badly formed: json}' value must be valid JSON.") 
Example #12
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_formfield(self):
        model_field = JSONField()
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, forms.JSONField) 
Example #13
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_formfield_disabled(self):
        class JsonForm(Form):
            name = CharField()
            jfield = forms.JSONField(disabled=True)

        form = JsonForm({'name': 'xyz', 'jfield': '["bar"]'}, initial={'jfield': ['foo']})
        self.assertIn('[&quot;foo&quot;]</textarea>', form.as_p()) 
Example #14
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_prepare_value(self):
        field = forms.JSONField()
        self.assertEqual(field.prepare_value({'a': 'b'}), '{"a": "b"}')
        self.assertEqual(field.prepare_value(None), 'null')
        self.assertEqual(field.prepare_value('foo'), '"foo"') 
Example #15
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_custom_widget_kwarg(self):
        """The widget can be overridden with a kwarg."""
        field = forms.JSONField(widget=widgets.Input)
        self.assertIsInstance(field.widget, widgets.Input) 
Example #16
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_custom_widget_attribute(self):
        """The widget can be overridden with an attribute."""
        class CustomJSONField(forms.JSONField):
            widget = widgets.Input

        field = CustomJSONField()
        self.assertIsInstance(field.widget, widgets.Input) 
Example #17
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_already_converted_value(self):
        field = forms.JSONField(required=False)
        tests = [
            '["a", "b", "c"]', '{"a": 1, "b": 2}', '1', '1.5', '"foo"',
            'true', 'false', 'null',
        ]
        for json_string in tests:
            val = field.clean(json_string)
            self.assertEqual(field.clean(val), val) 
Example #18
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_has_changed(self):
        field = forms.JSONField()
        self.assertIs(field.has_changed({'a': True}, '{"a": 1}'), True)
        self.assertIs(field.has_changed({'a': 1, 'b': 2}, '{"b": 2, "a": 1}'), False) 
Example #19
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_custom_widget_kwarg(self):
        """The widget can be overridden with a kwarg."""
        field = forms.JSONField(widget=widgets.Input)
        self.assertIsInstance(field.widget, widgets.Input) 
Example #20
Source File: fields.py    From cjworkbench with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_prep_value(self, value):
        if value is None:
            return None

        arr = [_column_to_dict(c) for c in value]
        return super().get_prep_value(arr)  # JSONField: arr->bytes 
Example #21
Source File: fields.py    From cjworkbench with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_prep_value(self, value):
        if value is None:
            return None

        arr = [_render_error_to_dict(re) for re in value]
        return super().get_prep_value(arr)  # JSONField: arr->bytes 
Example #22
Source File: submissions.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_data(self):
        # Updated for JSONField - Not used but base get_data will error
        form_data = self.form_data.copy()
        form_data.update({
            'submit_time': self.submit_time,
        })

        return form_data

    # Template methods for metaclass 
Example #23
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_default(self):
        class MyModel(PostgreSQLModel):
            field = JSONField(default={})

        model = MyModel()
        self.assertEqual(model.check(), [
            checks.Warning(
                msg=(
                    "JSONField default should be a callable instead of an "
                    "instance so that it's not shared between all field "
                    "instances."
                ),
                hint='Use a callable instead, e.g., use `dict` instead of `{}`.',
                obj=MyModel._meta.get_field('field'),
                id='postgres.E003',
            )
        ]) 
Example #24
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid_default(self):
        class MyModel(PostgreSQLModel):
            field = JSONField(default=dict)

        model = MyModel()
        self.assertEqual(model.check(), []) 
Example #25
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid_default_none(self):
        class MyModel(PostgreSQLModel):
            field = JSONField(default=None)

        model = MyModel()
        self.assertEqual(model.check(), []) 
Example #26
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_serializable(self):
        field = JSONField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(datetime.timedelta(days=1), None)
        self.assertEqual(cm.exception.code, 'invalid')
        self.assertEqual(cm.exception.message % cm.exception.params, "Value must be valid JSON.") 
Example #27
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_custom_encoder(self):
        with self.assertRaisesMessage(ValueError, "The encoder parameter must be a callable object."):
            field = JSONField(encoder=DjangoJSONEncoder())
        field = JSONField(encoder=DjangoJSONEncoder)
        self.assertEqual(field.clean(datetime.timedelta(days=1), None), datetime.timedelta(days=1)) 
Example #28
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid_empty(self):
        field = forms.JSONField(required=False)
        value = field.clean('')
        self.assertIsNone(value) 
Example #29
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid(self):
        field = forms.JSONField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean('{some badly formed: json}')
        self.assertEqual(cm.exception.messages[0], "'{some badly formed: json}' value must be valid JSON.") 
Example #30
Source File: test_json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_formfield(self):
        model_field = JSONField()
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, forms.JSONField)