2

I tried this code to save my JSON data to my model that is Mvouchar. But getting this error. I easily get data through cmd but I tried to save this in my model then I get the error, why this happens, I think am doing some minor mistake but can't catch please help if u get my problem

#views.py
@csrf_exempt
def jsdata(request):
    table_data = json.loads(request.POST.get('MyData'))
    print(table_data)
    for data in table_data:
	    b_no = request.POST['billno']
	    b_details = request.POST['billdetails']
	    at = request.POST['amount2']
	    record = Mvouchar(bill_no = data.b_no, bill_details = data.b_details,am=data.at)
	   record.save()
    return render(request, 'cheque/mvouchar.html', {'msg': 'Data Saved.'})
    
#models.py

class Mvouchar(models.Model):
	related = models.ForeignKey(Signs, on_delete=models.CASCADE, null=True, blank=True)
	bill_no = models.CharField(max_length=80, null=True, blank=True)
	bill_details = models.CharField(max_length=1000, null=True, blank=True)
	am = models.CharField(max_length=30, null=True, blank=True)
	vouchar_no = models.CharField(max_length=1000, null=True, blank=True)
  
#urls.py

url(r'jsondata/$', views.jsdata, name='jsondata'),

#script
<script>
$("#btnjson").click(function () {
			var array1 = [];
					$("tbody tr").each(function () {
                        var firstTableData = {};
                        firstTableData.BillNo = $(this).find('td').eq(0).text();
                        firstTableData.BillDetails = $(this).find('td').eq(1).text();
                        firstTableData.Amount = $(this).find('td').eq(2).text();
                        array1.push(firstTableData);
                    //}
                }); 
				alert(JSON.stringify(array1));
				 $.ajax({
				type: "POST",
				url: "/jsondata/",
				dataType: 'json',
				data: {MyData: JSON.stringify(array1)},
				success: function(msg){
                alert(msg);
            }
        });
        return false;
    } );
			});
</script>

15
  • Can you post table_data that is printing in your console. Commented Oct 25, 2018 at 8:25
  • This error probably occurs when the key not present in request data. Commented Oct 25, 2018 at 8:26
  • please see my question now i insert image with print table_data Commented Oct 25, 2018 at 8:31
  • 1
    From your ajax you are sending just one array MyData which contains your json string. How do you expect to get request.POST['billno'] in your view. It doesn't exists, you never sent it. I think in your ajax you should post data: JSON.stringify(array1), there is no need to put the json in another object. Commented Oct 25, 2018 at 8:33
  • 1
    nvm i see you are sending an array to create multiple objects, so the way you are sending json is alright. I was thinking you are going to create just one object. Commented Oct 25, 2018 at 8:49

4 Answers 4

1
from django.http import JsonResponse
    def jsdata(request):
        table_data = json.loads(request.POST.get('MyData'))
        # print(table_data)
        r_data = {
            'success': True,
        }
        for data in table_data:
            # Since you are just creating objects you don't need to save created object in a variable.
            try:
                Mvouchar.objects.create(bill_no = data['BillNo'], bill_details=data['BillDetails'],at=data['Amount'])
            except:
                r_data['success'] = False

        # IMO Views responding to ajax requests should send JsonResponse
        if r_data['success']:
            r_data['msg'] = 'Data Saved'
        else:
            r_data['msg'] = 'Not all Data Saved'
        return JsonResponse(r_data)
Sign up to request clarification or add additional context in comments.

9 Comments

hey does not show any error now i will fix but still does not save entry in my models
please see the image in question now no error but at submit data does not submit to my fields
i get two alert in first alert have my data but in second alert it shows [object Object]
so what happend with my data why its not connect to models now
|
0

This error probably occurs when the key not present in request data. By changing

b_no = request.POST['billno'] 

to

b_no = request.POST.get('BillNo').

solve throwing this exception. Even if data not present it returns None. Or can handle it by add try.except block.

try:
    b_no = request.POST['billno'] 
except KeyError:
    pass

And in your code, you call every dict key in lower case form and amount key as amount2. Change that to Amount

3 Comments

now its giving me typeError: method 'object' is not subscriptable
request.POST.get is a method, it needs parentheses () not square brackets [].
This also does not take into account that the key is not sent in request.POST but within a dictionary within a list within the key request.POST['Mydata'] instead...
0

If your are storing data in table_data (table_data = request.POST.get('MyData')) then use table_data to store it in models.

Your data is in dictionary form so need to call values by its keys. like -

@csrf_exempt
def jsdata(request):
    table_data = json.loads(request.POST.get('MyData'))
    print(table_data)
    for data in table_data:
        b_no = data.get('BillNo')
        b_details = data.get('BillDetails')
        at = data.get('Amount')
        record = Mvouchar(bill_no = b_no , bill_details = b_details ,am=at )
       record.save()
    return render(request, 'cheque/mvouchar.html', {'msg': 'Data Saved.'})

Try this and tell me if any error occurs.

3 Comments

hey @PankajSharma now am also getting error plz check trace in updated question
@monikachoudhary I can't understand which is current error trace and what updates you have made in your views.py
In which attribute you are getting error ? Also can post new question for this error
0

A KeyError is usually thrown when you look up a value for a key in a dictionary that does not exist. You could either provide a default value or check the existence of the key before you do the lookup.

request.POST.get('billno', 'default_value')

For more information about querying a dictionary with default values, see this helpful StackOverflow answer

The line above as such will not work, since there are other issues in this code besides the key not existing with only lowercase letters (see below).

Looking at the code I expect the key to not exist either because it has not been sent or because it may contain uppercase letters.

As it has been pointed out in the comments to your question, not only are you querying for billno (only lowercase letters) while the key you send has uppercase letters (BillNo), but you also embed it into another dictionary MyData - you need to change your query from request.POST['billno'] to data['BillNo'] (the same goes for all the other values you are trying to extract).

The correct query would thus look like this:

for data in table_data:
    b_no = data['BillNo']
    b_details = data['BillDetails']
    at = data['Amount']
    record = Mvouchar(bill_no = b_no, bill_details = b_details,am=at)
    record.save()

Comments

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.