嘿,我尝试了此代码,但仍然有一个不是Null约束失败的错误,我知道这是因为我的cheque_no是唯一类型,但是我如何才能删除此错误,但我没有删除我的cheque_no是唯一的,因为它是必需的。现在遇到了这个问题,我想将这些条目保存在我的模型中。
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;
} );
});
答案 0 :(得分: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')
...
答案 1 :(得分:0)
如果您阅读了第二条回溯(第一条回溯来自另一个视图views.mvoucha
,并且您没有在问题中包含该代码),您会发现问题出在您的视图中功能。
table_data = json.loads(request.POST.get('MyData'))
正在发生的事情是request.POST.get('MyData')
返回None
,它不能表示为json。这就是json编码器引发TypeError的原因。
request.POST
字典与表单数据一起使用。当您想解析json负载时,必须使用request.body
来代替。例如这样的
table_data = json.loads(request.body).get('MyData')
https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.POST