Django-Forms with json fields

django array field widget
django forms tutorial
python forms
django json builder
django search json field
django dynamic fields

I am looking to accept json data in a form field and than validate it using some database operations. The data will mostly consist of an array of integers. So can you please help me as to how can i do so.

I have tried to google this but didn't get any decent answer. Please help.

You need to take it as text input using CharField. And in the clean method of this field, you can validate it as per your requirement to check if input is valid.

Something like:

class myForm(forms.Form):
     jsonfield = forms.CharField(max_length=1024)

    def clean_jsonfield(self):
         jdata = self.cleaned_data['jsonfield']
             json_data = json.loads(jdata) #loads string as json
             #validate json_data
             raise forms.ValidationError("Invalid data in jsonfield")
         #if json data not valid:
            #raise forms.ValidationError("Invalid data in jsonfield")
         return jdata

You may also find a custom field for JSON data input.

PostgreSQL specific form fields and widgets, a string of JSON formatted data inside, this mixin adds handling of this. field to a ModelForm. It will read the text field, convert to Python dict, fill the form fields. A form field is provided that renders the dynamic form created by json-editor, loading in the provided schema and options along with any initial form data. The field can be rendered in the same way as any other django field and also validates submitted data against your json schema on submission.

You can make forms with fields from JSON data with that decision


# -*- coding: utf-8 -*-
from django import forms
from splitjson.widgets import SplitJSONWidget

class testForm(forms.Form):
    attrs = {'class': 'special', 'size': '40'}
    data = forms.CharField(widget=SplitJSONWidget(attrs=attrs, debug=True))

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from forms import testForm

def test_dict(request):
    json = {'a': 1,
            'b': 2,
            'c': 3,
            'd': 4}
    form = testForm(request.POST or None, initial={'data': json})
    if form.is_valid():
        # validate and save

    template = 'test_template.html'
    context = RequestContext(request, {'form': form})
    return render_to_response(template, context)

<!doctype html>
        {% for field, error in form.errors.items %}
            <li>{{ error }}</li>
        {% empty %}
            no errors 
        {% endfor %}
        List of:
            <form action="" method="post">
                {% csrf_token %}
                {{ form.as_p}}
                <input type="submit" value="Submit" />


JSONFieldFormMixin for Django ModelForm with JSON field · GitHub, A form field is provided that renders the dynamic form created by json-editor, loading in the provided schema and options along with any initial  If the built-in Field classes don’t meet your needs, you can create custom Field classes. To do this, create a subclass of django.forms.Field. Its only requirements are that it implement a clean() method and that its __init__() method accept the core arguments mentioned above (required, label, initial, widget, help_text).

Check django-json-field which implements JSONField and associated form field.

django-jsonforms · PyPI, django-json-field contains a flexible JSONField and associated form field. The model field is not only capable of serializing common JSON data types (int, float,​  Generic JSON model and form fields. Enables pretty JSON viewer in Django forms, admin, or templates Django form's widget that renders field JSON data as group fields that can edited. Django field subclasses for some PostgreSQL types. A JSONField for django.

There's the most popular github repository with JSONField implementation. You can install it with:

pip install jsonfield

For example, if you have a model

from jsonfield import JSONField
from django.db import models

class MyModel(models.Model):
    json_field = JSONField(default='', blank=True)

You can simply define a form with JSON validation

from django import forms
from jsonfield.fields import JSONFormField
from myapp import models

class MyModelForm(forms.ModelForm):
    class Meta:
        model = models.MyModel
        fields = '__all__'
        field_classes = {
            'json_field': JSONFormField,

and use this form in your admin model

from django.contrib import admin

from myapp.forms import MyModelForm
from myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

django-json-field · PyPI, A JSONField for django. Edit JSON-Model Fields using a. Standard Django Form. Python implementation of the (inactive) HTML JSON Forms spec. Makes  Field.get_bound_field(form, field_name)¶ Takes an instance of Form and the name of the field. The return value will be used when accessing the field in a template.

django.contrib.postgres has a JSONField form field. Here is a link to docs. Field is represented by an HTML <textarea>.

from django import forms
from django.contrib.postgres.forms.jsonb import JSONField

class ExampleForm(forms.Form):

    metadata = JSONField()

JSON fields, JSONFields in Forms¶. By default this uses the simple Django-MySQL form field JSONField , which simply displays the JSON in an HTML <textarea> . django-entangled. Edit JSON-Model Fields using a Standard Django Form. Use-Case. A Django Model may contain fields which accept arbitrary data stored as JSON. Django itself, provides a JSON field specific to Postgres. For other database implementations, there are plenty of alternatives.

JSONField, A JSON described django form is just an array of field JSON objects. Each field object has three required attributes: name which is the keyword of  json_storage_field: which field of the model holds the JSON data, should only be text Attributes on form.Meta: json_fields: the fields to read and save, need to be model fields defined on ModelForm

Django dynamic forms, Compared to its model fields, Django's form fields are easier to write. However, with the JSONField form field available in contrib.postgres  The Form class is the heart of Django's form handling system. It specifies the fields in the form, their layout, display widgets, labels, initial values, valid values, and (once validated) the error messages associated with invalid fields.

Form field and database feature :: laymonage's gsoc blog, In this post I'll show a few tricks I use to make JSON fit into Django more The second field has JSON validation wired to it so the form won't go  The concepts of form fields combined with widgets can go a long way in streamlining the interface to interact with data. We propose an architecture to serialize information about django forms (to JSON) in a framework independent fashion so that it can be consumed by any frontend application that renders HTML.

  • Do you think making a custom field for json data will be a better option?? I also thought that but couldn't decide on it whether it was the best option or not?
  • @SaranshMohapatra, custom field would we good if you this is one of major functionalities. If this is one of then it may be little too much. Also, instead of writing new, look for any existing implementations.
  • @Rohan I got red zigzag line in PyCharm asking me import the module.
  • @Sarit for python 2.6+ use import json