我一直試圖弄清楚幾個小時,並相信我,我真的無處不在堆棧溢出。將ForeignKey添加到UserProfile中給出外鍵約束失敗
在我的UserProfile中,我有一個到另一個模型(稱爲「公司」)的ForeignKey引用,並且在註冊後,我創建一個新公司並將UserProfile ForeignKey指向該公司。
models.py如下:
class UserProfile(models.Model):
company = models.ForeignKey(Company)
title = models.CharField(max_length = 50, default = '')
user = models.OneToOneField(User, default = 0, null = True)
class Company(models.Model):
"""A company profile."""
name = models.CharField(max_length = 50)
我用一個表格來進行數字簽名了。這裏的形式:
class SignupForm(ModelForm):
name = forms.CharField(label = "Name")
company = forms.CharField(max_length = 50)
email = forms.EmailField(label = "Email")
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ("name", "company", "email", "password")
def save(self, commit=True):
user = super(SignupForm, self).save(commit=False)
name = self.cleaned_data["name"].split()
if len(name) == 1:
# User did not enter a last name.
user.first_name = name
else:
user.first_name, user.last_name = name
user.email = self.cleaned_data["email"]
user.set_password(self.cleaned_data["password"])
user.username = user.email
if commit:
user.save()
return user
和這裏的註冊視圖:
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
# Check if email has already been used for an account.
email = request.POST['email']
existing_account = User.objects.filter(email = email)
if existing_account:
form = SignupForm()
return render_to_response('registration/signup.html',
{ 'form': form,
'error': 'duplicate_email',
})
# Otherwise, save the form and create a new user.
new_user = form.save()
company = Company(name=request.POST['company'])
company.save()
user_profile = new_user.get_profile()
user_profile.company = company
user_profile.save()
new_user = authenticate(
username = email,
password = request.POST['password']
)
# Log the user in automatically.
login(request, new_user)
# Redirect user to Thank You page.
return HttpResponseRedirect('/thanks')
else:
form = SignupForm()
return render_to_response('registration/signup.html', {
'form': form,
})
我正在告訴我,COMPANY_ID錯誤不能爲空。我明確地增加了一家新公司。請讓我知道你的想法可能是錯誤的。
感謝
請粘貼錯誤。我想知道該行 – Goin
感謝您的回覆。錯誤中引用的行是:new_user = form.save()和user.save()。錯誤是(1048,「Column'company_id'不能爲空」) –