Back to Home

Django: form widget for JSON editing

The format for presenting data in the form of JSON is not uncommon. For example · one of the applications can be the exchange of JSON data when working with a third-party service API · and in other cases JSON data can ...

Django: form widget for JSON editing

    The format for presenting data in the form of JSON is not uncommon. For example, one of the applications can be the exchange of JSON data when working with a third-party service API, and in other cases JSON data can be stored inside the application model. In some cases, the data must be changed and sent back to the remote service, in others, saved in the model.



    If we recall the forms and widgets of forms in Django - powerful tools that simplify the work. And then refer to the source code and official documentation, we will see a list of almost 20 ready-made widgets that are available to us. In addition to official sources, there is a translation into Russian .
    Unfortunately, there is nothing ready to find there that would facilitate working with JSON data in forms. If you turn to search engines, you can find several posts on stackoverflow and private blogs that offer solutions that will work for some cases. Unfortunately, some examples stop working on data with a complex nested JSON structure, while others require the use of JavaScript for serialization and the reverse process.

    I tried to find a solution that:
    • firstly, it will not require additional elements, such as using JavaScript
    • secondly, it will be able to work with nested complex JSON structures
    • thirdly, it will allow you to more clearly and conveniently edit JSON

    The solution was found in the form of a widget for the form. Here is a demonstration of how a widget builds a form from JSON and, after saving, reassembles it into JSON:

    image

    I hope that it can make life easier for someone other than me. Perhaps someone can offer improvements and / or constructive criticism.

    The solution and examples are posted on Github

    Read Next