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?

1
  • Is django 3.3 even out yet? Commented Oct 8, 2021 at 4:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Using CharField help to store data. But to avoid risk for max_lenght issue, i am using TextField .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.