DEV Community

Sami Ullah Saleem
Sami Ullah Saleem

Posted on

How to create a JSON field in Django to store an array from frontend

  1. pip install django-jsonfield
  2. Example to import it in model
import jsonfield from django.db import models class StudentData(models.Model): name=models.CharField(max_length=100) standard=models.CharField(max_length=100) section=models.CharField(max_length=100) the_json = jsonfield.JSONField() 
Enter fullscreen mode Exit fullscreen mode
  1. How to use it in views? Example
from django.shortcuts import render from . import models import json from django.http import JsonResponse # Create your views here. def test(request): if request.method == 'GET': alldata = models.dataM.objects.values('data') return render(request, 'index.html', {"datas": alldata}) else: print("value1: " + request.POST['data']) data = models.dataM.objects.create(data=request.POST['data']) data.save() alldata = models.dataM.objects.values('data') return render(request, 'index.html', {"datas": alldata}) 
Enter fullscreen mode Exit fullscreen mode

As you can see I am getting values of json field data and simply sending to html

Top comments (0)