当表单的字段为空时,出现以下错误:
/ inscription的IntegrityError
NOT NULL约束失败:le_site_inscrit.age
我的模特:
class Inscrit(models.Model):
user = models.OneToOneField(User)
age = models.IntegerField(max_length=2, null=True, default=None)
我在forms.html中的表单:
class inscriptionForm(forms.Form):
mail = forms.EmailField(max_length=100)
firstname = forms.CharField()
username = forms.CharField()
age = forms.IntegerField(required=False)
mdp = forms.CharField(widget=forms.PasswordInput)
我的看法:
def inscription(request):
error = False
if request.method == "POST":
form = inscriptionForm(request.POST)
if form.is_valid():
mail = form.cleaned_data["mail"]
mdp = form.cleaned_data["mdp"]
username = form.cleaned_data["username"]
userfirstname = form.cleaned_data["firstname"]
age = form.cleaned_data["age"] or None
u = User.objects.create_user(username,mail,mdp)
u.first_name = userfirstname
u.save()
inscrit = Inscrit()
inscrit.user = u
if age is not None :
inscrit.age = age
inscrit.save()
return redirect(reverse(home))
else :
error = True
else :
form = inscriptionForm()
return render(request,"zouya/inscription.html",locals())
谢谢
最佳答案
将blank=True
添加到模型字段定义中:
class Inscrit(models.Model):
user = models.OneToOneField(User)
age = models.IntegerField(max_length=2, null=True, blank=True, default=None)
关于python - Django-IntegrityError-不是null约束,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27881947/