NOT NULL约束失败 - django

时间:2017-08-25 04:43:39

标签: django

这类似于我前一段时间发布的一个问题,但我有不同的情况。我有一个模型,附有模型的表单。我得到一个非空约束,但没有任何字段为null,因此约束失败不应该出现。我不确定这个约束失败的来源是什么......有人可以帮助我,以防万一我看不到它。

models.py

dob_month = models.IntegerField(default=0)
dob_day = models.IntegerField(default=0)
dob_year = models.IntegerField(default=0)

views.py部分

dob_month = form.cleaned_data.get("dob_month")
dob_day = form.cleaned_data.get("dob_day")
dob_year = form.cleaned_data.get("dob_year")

new_profile = Profile.objects.create(
                user = currentUser,
                first_name = first_name,
                last_name = last_name,
                dob_month = dob_month,
                dob_day = dob_day,
                dob_year = dob_year,
                city = city,
                state = state,
                phone = phone,
                privacy = privacy,
)

表格后请求

dob_month : '6'
dob_day : '14'
dob_year : '2019'

这是即将出现的确切错误......

IntegrityError at /setup_profile/
NOT NULL constraint failed: tab_profile.dob_day
Request Method: POST
Request URL:    http://127.0.0.1:8000/setup_profile/
Django Version: 1.8.6
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: tab_profile.dob_day

已更新

这是forms.py部分......

class ProfileForm(forms.ModelForm):
    split_choices = (('1', 'public'),
                     ('2', 'private'))
    privacy = forms.TypedChoiceField(
        choices=split_choices, widget=forms.RadioSelect, coerce=int
    )
    dob = forms.DateField(widget=extras.SelectDateWidget)
    class Meta:
        model = Profile
        fields = ['first_name', 'last_name', 'dob', 'city', 'state', 'phone', 'privacy']

1 个答案:

答案 0 :(得分:1)

我猜这个问题是由于数字字段中的字符串插入而发生的

所以试试这个,希望它能解决错误

class MetaManager(MetaComponent):
    def __init__(cls, *args, **kwargs):
        super().__init__(*args, **kwargs)
        cls.SubManagers = [] # each class gets its own SubManagers list

    def ListSubManagers(cls):
        for manager in cls.SubManagers:
            print(manager)

    def RegisterSubManager(cls, manager):
        cls.SubManagers.append(manager)
        return manager

class Manager(Component, metaclass=MetaManager): # inherit from this to get the metaclass
    pass

class Manager1(Manager):
    pass

@Manager1.RegisterSubManager
class Manager2(Manager):
    pass

@Manager2.RegisterSubManager
class Manager3(Manager):
    pass