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如何使用單個表單填充兩個模型
你已經預先在客戶賬戶表填充的數據? –
是的,我有兩個對象 –
如果用戶是外鍵,我可能建議你在用戶字段中添加'null = True'。由於您正在將OnetoOne字段連接到用戶,因此您無法應用'null = True',我建議您刪除數據庫中的兩條記錄並嘗試應用遷移 –