当我的表单字段为空时,我有这个错误:
IntegrityError at / 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)
我在form.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())
由于
答案 0 :(得分:3)
将blank=True
添加到模型字段定义中:
class Inscrit(models.Model):
user = models.OneToOneField(User)
age = models.IntegerField(max_length=2, null=True, blank=True, default=None)