Issue storing multi valued json format dictionary into mysql table in DJango

Question!

I have below ajax call in my template

temp.html

function saveprof() {
            $.ajax({
                type: "POST",
                url: "saveprof",
                async: true,
                data: {
                    'radinput_Aj' : fun(),
                    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
                },
                success: function (data, textStatus, jqXHR) {
                    $('#message').html(data);
                }
            });
        }

fun() returns a json format object v - which is as below :

example :

var v = [
             { axis: "", value: 4, order: 0 },
             { axis: "", value: 4, order: 1 },
             { axis: "", value: 4, order: 2 },
             { axis: "", value: 4, order: 3 },
             { axis: "", value: 4, order: 4 },
             { axis: "", value: 4, order: 5 },
             { axis: "", value: 4, order: 6 }
    ];

Views.py

def saveprof(request):
if request.method == "POST":
    radinputV=[]
    radinputV = request.POST.get('radinput_Aj')
else:
    response_data = 'Nothing to update!'
    return HttpResponse(response_data, content_type="text/plain")
response_data = ''
try:
*(Here, I would like to insert the incoming dictionary (radinputV) rows into my model skills)*
except:
    response_data = 'Ouch! Something went wrong!'
return HttpResponse(response_data, content_type="text/plain")

Below is the skills model :

class skills(models.Model):
id = models.CharField(max_length=300,blank=True)
skill = models.CharField(max_length=300,blank=True)
rating = models.CharField(max_length=300,blank=True)
ordernum = models.CharField(max_length=300,blank=True)

Here is the mapping of incoming json dictionary from template with the fields in skills model - skill is axis, rating is value, ordernum is order

In the view :

radinputV=[]
radinputV = request.POST.get('radinput_Aj')
radinputV1 = request.POST.get('radinput_Aj[0][value]')

I can access dictionary item by using above notation.

However, if I use above notation, I would need to write 21 statements like this (7 rows * 3 columns) of Dictionary object V... is there a simple way for this ?

How to handle this scenario of inserting multiple rows into mysql table from template JSON object - Django view ?

Edited with the latest try using get method.



Answers

You can't send a data structure like this via standard form parameters. You need to serialize it to JSON before sending, and then deserialize it in the view.

Change the data parameter as follows:

data: {
    'radinput_Aj' : JSON.stringify(fun()),
    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},

and the view:

if request.method == "POST":
    data = request.POST.get('radinput_Aj')
    radinputV = json.loads(data)


This video can help you solving your question :)
By: admin