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

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup πŸš€

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging β†’

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay