将JSON数据发布到模型时,Django Not null约束失败 [英] Django Not null constraint failed while posting json data to models

查看:167
本文介绍了将JSON数据发布到模型时,Django Not null约束失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我尝试了此代码,但仍然有一个不是Null约束失败的错误,我知道这是因为我的cheque_no是唯一类型,但是我如何才能删除此错误,但我没有删除我的cheque_no是唯一的,因为它是必需的.现在遇到了这个问题,我想将这些条目保存在我的模型中.

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

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

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;
    } );
            });

推荐答案

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')

    ...

这篇关于将JSON数据发布到模型时,Django Not null约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆