2016-04-21 58 views
0
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如何使用單個表單填充兩個模型

+0

你已經預先在客戶賬戶表填充的數據? –

+0

是的,我有兩個對象 –

+0

如果用戶是外鍵,我可能建議你在用戶字段中添加'null = True'。由於您正在將OnetoOne字段連接到用戶,因此您無法應用'null = True',我建議您刪除數據庫中的兩條記錄並嘗試應用遷移 –

回答

0

由於您收到非空錯誤,我認爲您需要指定該字段不是必需的。這是我的一個應用程序的例子。這表示表單字段不是必需的。

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 

我也包括這在我的模型,使我的模型字段可以爲空,這樣的:

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

如果我仍然可以不爲空的錯誤我兩者都做的這些事情後,我補該領域具有佔位符的價值,可以讓我進一步調查問題。

+0

你說的只有當它是一個FK,你不能有'null = True'到OnetoOne字段 –

0

您已將表格中的用戶從保存方法中刪除,並且您已在保存方法中指定了self.user。因此,在保存表單時,用戶屬性不用於CustomAccountForm,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() 
+0

現在我正在獲取唯一約束失敗:mylogin_customaccount.user_id錯誤 –

+0

這意味着您正在使用同一用戶創建多個CustomAccount對象。 –

+0

這怎麼可能我在保存每個時間之前創建新用戶 –

相關問題