如何使用单个表单填充两个模型

时间:2016-04-21 09:48:34

标签: django forms python-2.7

  class CustomAccount(models.Model):
        user = models.OneToOneField("auth.User")
        role =  models.CharField(max_length = 50,   default = 'student',    choices=APPROVAL_CHOICES)
        balance = models.FloatField( default = 0 )
        timezone = models.CharField(max_length = 200)
        def __str__(self):

            return self.user.username +" ["+ self.role + "]"

    class CustomAccountForm(forms.ModelForm):
        username = forms.CharField(max_length=30 )
        email = forms.EmailField(max_length=255 )
        password1 = forms.CharField(label= "Password",widget=forms.PasswordInput())
        password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput , help_text="Enter the same password as above, for verification.")    

        def save(self, commit= True):
            user = User.objects.create_user(username = self.cleaned_data['username'], email = self.cleaned_data['email'] , password = self.cleaned_data['password1'])
            user.save()
            self.user = user
            return super(CustomAccountForm, self).save(commit=commit)

        def clean_username(self):
            username = self.cleaned_data["username"]
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                return username
            raise forms.ValidationError("A user with that username already exists.")

        def clean_password2(self):
            password1 = self.cleaned_data.get("password1", "")
            password2 = self.cleaned_data["password2"]
            if password1 != password2:
                raise forms.ValidationError("The two password fields didn't match.")
            return password2
        def clean_email(self):
            email = self.cleaned_data["email"]
            try:
                User.objects.get(email=email)
            except User.DoesNotExist:
                return email
            raise forms.ValidationError("A user with that emailaddress already exists.")    
        class Meta:
            model = CustomAccount       
            exclude = ['balance','user']

我想在Django Admin部分使用包含auth.User和CustomAccount Model字段的单一表单创建自定义帐户。我在/ admin / mylogin / customaccount / add /中收到错误IntegrityError NOT NULL约束失败:mylogin_customaccount.user_id

2 个答案:

答案 0 :(得分:0)

由于您收到非null错误,我认为您需要指定该字段不是必需的。以下是我的某个应用中的示例。这表示不需要表单字段。

class arunModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        myuser = kwargs.pop('user', None)
        super(arunModelForm, self).__init__(*args, **kwargs)

        self.fields['nanoadded'].required = False
        self.fields['response'].required = False

我还在我的模型中包含了这个,以便我的模型字段可以为null,如下所示:

class arun(models.Model):
    auser = models.CharField(max_length=50, null=True)
    adate = models.DateField(null=True)
    atime = models.TimeField(null=True)

如果在执行这两项操作后仍然没有出现空错误,我会在字段中填入占位符值,以便我进一步调查问题。

答案 1 :(得分:0)

您已从表单中删除了用户,并且在save方法中,您已在save方法中指定了self.user.因此,在保存表单时,CustomAccountForm不使用user属性,CustomAccount的用户字段为None。

您的保存方法应如下所示:

def save(self, commit= True):
    user = User.objects.create_user(username =self.cleaned_data['username'], email = self.cleaned_data['email'] ,     password = self.cleaned_data['password1'])
    user.save()
    obj = super(CustomAccountForm, self).save(commit=False)
    obj.user = user
    obj.save()