1

As we know, Django=3 is supporting JSONField . I am trying to save JSON data in my Django Project using JavaScript, i have take data in a input field which looks like:

[{"id":1,"Name":"Antenna","Pieces":"","Weight":"","Weight Types":"","Quantity":"12",
    "Cargo Charge":"12","Customs Charge":"12"},

{"id":2,"Name":"Soap","Pieces":"12","Weight":"12","Weight Types":"","Quantity":"",
    "Cargo Charge":"12","Customs Charge":"12"}]

From the input field I save the data to MySql database using .

product_list = self.request.POST['product_list_json']

Hence, product_list_json is the name of the inout field. But the saving data is given different view, the saved data look like:

"[{\"id\":1,\"Name\":\"Antenna\",\"Pieces\":\"\",\"Weight\":\"\",\"Weight Types\":\"\",
    \"Quantity\":\"12\",\"Cargo Charge\":\"12\",\"Customs Charge\":\"12\"},
{\"id\":2,\"Name\":\"Soap\",\"Pieces\":\"12\",\"Weight\":\"12\",\"Weight Types\":\"\",
    \"Quantity\":\"\",\"Cargo Charge\":\"12\",\"Customs Charge\":\"12\"}]"

The problem is that, data is saving with additional " \ " . What can i do to solve this?

2 Answers2

0

Jsonfield in Django, takes a dict or a list and convert them to JSON (str) and saves them in DB, just load the received JSON from request.POST and send it and it will work fine.

Mohamed ElKalioby
  • 1,908
  • 1
  • 12
  • 13
0

Simple CharField can work for you. It can work something like this.

models.py

class subscription_info(models.Model):
     info=models.CharField(max_length=2000,null=True,blank=True)

views.py

from myApp.models import subscription_info as sInfo

def For_AJAX(request):
    if request.method=='POST':
        data=request.body.decode('utf-8')
        mymodel=sInfo()
        mymodel.info=data
        mymodel.save()
        return HttpResponse(status=201)
    else:
       return HttpResponse(status=204)

def For_Form(request):
        if request.method=='POST':
            data=request.POST.get('InputFieldName')          
            mymodel=sInfo()
            mymodel.info=data
            mymodel.save()
            return HttpResponse(status=201)
        else:
           return HttpResponse(status=204)

Use json.loads() or json.dumps() as per your requirement after retrieving data from db.

itsmehemant7
  • 339
  • 1
  • 8