'How to create a code field in django form and save it as a json to the db

I am having a usecase where I want to have a code snippet field in django and use that code field value and save it as a json in the DB.

class TestForm(forms.Form):
    rule_name = forms.CharField(max_length=200)
    rule_code = forms.CharField(max_length=200)

the rule_code field should be able to accept code and when reading I should be able to parse as json.

eg:

rule_code = a+b

while parsing it should be as json. eg:

{"data":{"lval":"a", "rval": "b", "log":"+"}}

any suggestion will be helpful. Thanks



Solution 1:[1]

It's called a JSONField, and it's part of django's core framework:

my_json = models.JSONField(encoder=None, decoder=None, **options)

Django Documentation here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nowshad Ruhani Chowdhury