DEV Community

Sami Ullah Saleem
Sami Ullah Saleem

Posted on

1

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay