IntegrityError:App_userprofile.user_id可能不为NULL

时间:2016-03-27 12:43:08

标签: python django django-models django-forms django-views

我在该页面上工作,用户可以在其中编辑他/她的一些属性,如电话。

问题是这些属性可以存储在内置用户模块中,也可以存储在UserProfileuser = OneToOneField(User))中。

所以我已经创建了自定义表单进行更新。如果用户转到xxx/edit-profile,则这些表单由useruser.userprofile实例填充。问题是,由于我未在此表单中包含所有字段,因此在form.save()期间,错误正在被提出:

IntegrityError: App_userprofile.user_id may not be NULL

要清楚,我附上表格,模型和视图:

形式:

class UserUpdateForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('last_name','first_name',)

class UserProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('telephone',)

查看:

@login_required
def edit_user(request):
    user = request.user
    user_profile = user.userprofile

    if request.method=='POST':
        user_profile_update_form = UserProfileUpdateForm(request.POST)
        user_update_form = UserUpdateForm(request.POST)
        if user_profile_update_form.is_valid() and user_update_form.is_valid():

            user_update_form.save()
            user_profile_update_form.save()

            return render(request,'auth/profiles/my-profile.html')
        else:
            print user_profile_update_form.errors
            print user_update_form.errors
    else:

        user_profile_update_form = UserProfileUpdateForm(instance=user_profile)
        user_update_form = UserUpdateForm(instance=user)
        return render(request,'auth/profiles/edit-profile.html',
                      context={'user_profile_update_form':user_profile_update_form,
                               'user_update_form':user_update_form})

MODEL:

class UserProfile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='userprofile')

    # ATRIBUTY KTORE BUDE MAT KAZDY
    telephone = models.CharField(max_length=40,null=True)

    HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = (
            ('coincidence',u'It was coincidence'),
            ('relative_or_friends','From my relatives or friends'),
            )
    how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True)

    MARITAL_STATUS_CHOICES = (
        ('single','Single'),
        ('married','Married'),
        ('separated','Separated'),
        ('divorced','Divorced'),
        ('widowed','Widowed'),
    )
    marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True)

    # OD KIAL STE SA O NAS DOZVEDELI
    # A STAV

    def __unicode__(self):
        return '{} {}'.format(self.user.first_name,self.user.last_name)

    def __str__(self):
        return '{} {}'.format(self.user.first_name,self.user.last_name)

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我想这不是一种常规方式,但它有效。关键是如果我想保存表单,则会有空字段(例如ID)。

因此,我从这些表单中提取数据(以字典格式),并使用此数据设置当前记录的用户属性。因此,用户保持他的属性和那些在形式上的属性被改变。

        if user_profile_update_form.is_valid() and user_update_form.is_valid():

            for k, v in user_update_form.cleaned_data.iteritems():
                exec (u"user.{} = '{}'".format(k, v))
            for k, v in user_profile_update_form.cleaned_data.iteritems():
                exec (u"user.userprofile.{} = '{}'".format(k, v))
            user.save()
            user_profile.save()