0

hey i tried this code but still have an error that is Not Null constraint failed i know this is because of my cheque_no that is unique type but how could i remove this error i did not remove my cheque_no is unique because its required.now am getting this problem i want to save these entries in my model.

views.py

@csrf_exempt            
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.
                Mvouchar.objects.create(bill_no = data['BillNo'], bill_details=data['BillDetails'],am=data['Amount'])
               # 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)

models.py

class Mvouchar(models.Model):
    related = models.ForeignKey(Signs, on_delete=models.CASCADE, null=True, blank=True)
    bill_no = models.CharField(max_length=8000, null=True, blank=True)
    bill_details = models.CharField(max_length=10000, null=True, blank=True)
    am = models.CharField(max_length=30000, null=True, blank=True)
    cheque_no = models.PositiveIntegerField(validators=[MaxValueValidator(6)], unique=True, help_text='integers only')
    def __str__(self):
      if self.related:
        return self.related.relation.username.title()
      else:
        return 'no related!'
    class Meta:
        verbose_name_plural = "Single Cheque Multiple Vouchar Of Users"

javascript

$("#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;
    } );
            });
8
  • this error is raised because check_no is going Null from front-end cheque_no = models.PositiveIntegerField(validators=[MaxValueValidator(6)], unique=True, help_text='integers only', null=True) use this code in model.py Commented Oct 26, 2018 at 5:24
  • hey its remove error but happning somthing weired Commented Oct 26, 2018 at 5:32
  • means the value of bill_no bill_details and amount are save in not_related field and how many entries are written then not_related field created accordingliy Commented Oct 26, 2018 at 5:34
  • and the entry does not get in the model that is full form submitted Commented Oct 26, 2018 at 5:35
  • please check images what happening Commented Oct 26, 2018 at 5:46

2 Answers 2

1
from django.core.validators import RegexValidator

CHEQUE_REGEX = RegexValidator( 
    regex=r'^\d{6}$', 
    message="Cheque Number must be exactly 6 digits" 
)

class Mvouchar(models.Model):
    ...

    cheque_no = models.CharField(validators=[CHEQUE_REGEX, ], unique=True, max_length=6, help_text='integers only')

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

Comments

0

If you read the second traceback (The first traceback is from a different view views.mvoucha, and you didn't include that code in the question), you'll find that the problem is this line in your view function.

    table_data = json.loads(request.POST.get('MyData'))

What's happening is that request.POST.get('MyData') returns None, which can't be represented as json. That's why the json encoder raises a TypeError.

The request.POST dictionary is used with form data. When you want to parse a json payload, you have to use request.body instead. For example like this:

    table_data = json.loads(request.body).get('MyData')

https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.POST

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.