/的IntegrityError

时间:2018-08-12 11:11:17

标签: django django-models django-forms

我一直在尝试使用django.contrib.auth.models的内置User创建用户个人资料表单。一切工作正常,但是将字段填充到表单中(正在显示)后,我遇到了完整性错误,提示“ NOT NULL CONSTRAINT失败”。 You can see this image using this link to know exactly what the error is showing.

这是我的models.py文件

from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator
# Create your models here.
class UserProfileInfo(models.Model):

    user = models.OneToOneField(User,on_delete=models.CASCADE, null=True)
    phone_number = models.PositiveIntegerField(validators= 
    [MaxValueValidator(9999999999)],blank=True)


    def __str__(self): #This will print out this model
         return self.user.username

这是我的forms.py文件。

from django import forms
from django.contrib.auth.models import User
from Login_Signup_Form.models import UserProfileInfo

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

class Meta:   
    model=User
    fields=('first_name','last_name','username','email','password',)

    class UserProfileForm(forms.ModelForm):
        class Meta:
             model=UserProfileInfo    #this is model
             fields=('phone_number',)

这是我的views.py文件。

from django.shortcuts import render
from Login_Signup_Form.forms import UserForm,UserProfileForm
from Login_Signup_Form.models import UserProfileInfo
# Create your views here.

def index(request):
   return render(request,'base.html')

def register(request):
   registered=False

   if request.method == 'POST':
      user_form = UserForm(data=request.POST)  
      user_phone_number=UserProfileForm(data=request.POST)

        if user_form.is_valid() and user_phone_number.is_valid():
            user=user_form.save()
            user.set_password(user.password)
            user.save()

            phone = user_phone_number.save()
            phone.user=user    
        else:
            #Printing the errors
            print(user_form.errors,user_phone_number.errors)
   else:
        user_form = UserForm()
        user_phone_number = UserProfileForm()


  return render(request, 'base.html',{'user_form':user_form, ' 
phone_number':user_phone_number})

1 个答案:

答案 0 :(得分:0)

该错误可能是由您表格中的空电话号码引起的。您可以在表单中使用blank=True来允许一个空的phone_number,但是在数据库级别上不允许它,还需要添加null=True

phone_number = models.PositiveIntegerField(validators= 
[MaxValueValidator(9999999999)], blank=True, null=True)

请参见this great answer

使用blank=True时,该字段不是必需的,并且该表单将进行验证,但是由于null=True不在此处,因此它将引发完整性错误。对于CharField不会发生这种情况,空白值将存储为空字符串。这仅是由于PositiveIntegerField造成的。