我有一个简单的表单,其中包含文本字段和单选按钮 系统在其中接受用户输入并将新记录添加到数据库中。
用户填写表单并点击提交按钮后,系统显示以下错误的问题:
返回Database.Cursor.execute(自身,查询,参数) django.db.utils.IntegrityError:NOT NULL约束失败: map_person.gender
class Person(models.Model):
boolChoice = (
("M","Male"),("F","Female")
)
name = models.CharField(max_length=50)
date = models.DateField()
description = models.TextField()
gender = models.CharField(max_length=10, choices= boolChoice)
def __str__(self):
return str(self.name)
{% extends 'base.html' %}
{% block content %}
<div class="hero__content">
<form method="POST" class="form-style-9">{% csrf_token %}
{{ form.as_p }}
<ul>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<li>
<h2>Add Member</h2>
</li>
<li>
<input type="text" name="name" class="field-style field-split align-right" placeholder= "enter ur name " id="name"/>
</li>
<li>
<input type="date" name="date" class="field-style field-full align-none" placeholder= " your birthdate" id="birthdate" />
</li>
<li>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
</li>
<li>
<textarea name="description" class="field-style" placeholder= "introduce yourself " id="description"></textarea>
</li>
<li>
<input type="submit" class="field-style field-full align-none" id="save" value="ADD" />
<script type="text/javascript">
$(function(){
$('#save').on('click',function(e){
e.preventDefault()
name=$('#name').val()
birthdate=$('#birthdate').val()
description=$('#description').val()
radioValue = $("input[name = 'gender']:checked").val()
if (radioValue){
alert("radioValue =", radioValue)
}
alert("name =", name)
alert("date =", birthdate)
alert("desc =", description)
$.ajax({
url:'/addperson/',
method:'POST',
data: {
na:name,
bi:birthdate,
de:description,
ra:radioValue
},
headers:{
'X-CSRFToken':'{{csrf_token}}'
}
}).done(function(msg) {
document.location = "/home.html"
alert('ﻟﻘﺪ ﺗﻢّ ﺣﻔﻆ اﻟﻤﻌﻠﻮﻣﺎﺕ')
}).fail(function(err){
alert('ﻟﻢ ﻳﺘﻢ اﻟﺤﻔﻆ')
})
})
})
</script>
</li>
</ul>
</form>
</div>
{% endblock %}
def addperson(request):
print("request method = " , request.method)
if request.method == "POST":
name = request.POST['na']
birthdate = request.POST['bi']
description=request.POST['de']
radiovalue=request.POST['ra']
person=Person.objects.create(
name=name,
date=birthdate,
description=description
)
person.save()
return render(request,'./home.html')
else:
print("this is a get METHOD")
答案 0 :(得分:1)
好吧,当您创建人时,您并没有设置性别,因此,没有空约束。
person=Person.objects.create(
name=name,
date=birthdate,
description=description,
# set gender here
)
这是分割html文件和javascript文件的更好的做法。 使用javascript行尾的半冒号也是一种好习惯。
在这里进行ajax调用重要吗?因为使用django.forms.ModelForm
来进行您的操作会更加简单和正确(因为ajax调用成功后会重定向)。
如果您希望页面在提交时不刷新,那么ajax是不错的选择。