Django - IntegrityError - 非空约束

Django - IntegrityError - Not null constraint

当我的表单字段为空时,出现此错误:

/inscription 处出现完整性错误 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)