问题
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;
} );
});
回答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')
...
回答2:
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
来源:https://stackoverflow.com/questions/53001915/django-not-null-constraint-failed-while-posting-json-data-to-models