将ForeignKey添加到UserProfile,给出外键约束失败

时间:2012-05-11 21:40:47

标签: django

我一直在努力解决这个问题几个小时,相信我,我真的在Stack Overflow上到处寻找。

在我的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不能为空。我明确地添加了一家新公司。请让我知道你认为可能是错的。

由于

2 个答案:

答案 0 :(得分:0)

我今天有这个确切的错误,没有任何理由,除了它是由SQLite引起的。使用SQLite,一个表的id字段从INTEGER PRIMARY KEY变为INTEGER。如果您正在使用SQLite,请尝试删除有问题的表并使用syncdb重新创建它。

的价值是多少?
user_profile = new_user.get_profile()

答案 1 :(得分:0)

不确定这对你的品味是否过于苛刻,但也许你可以创建/保存Company对象并将其作为位置/关键字参数传递给你的SignupForm.save()方法。

你到达那里的问题是你期待一个CharField并且你正在传递公司对象。因此,您可能希望将company.pk提供给表单中的公司字段。