2017-01-14 151 views
0

我有以下視圖,其完美地工作:的Django - >異常值:(1048,「列‘USER_ID’不能爲空」)

@transaction.atomic 
def register(request): 
    next_url = request.POST.get('next', request.GET.get('next', reverse('profile'))) 
    if request.method == 'POST': 
     form = RegistrationForm(request.POST) 
     profileform = ProfileForm(request.POST) 
     if form.is_valid() and profileform.is_valid(): 
      new_user = form.save() 

      # Login the newly created user. 
      authenticated_user = authenticate(username=new_user.username, 
               password=form.cleaned_data['password1']) 
      login(request, authenticated_user) 
      return redirect(next_url) 
    else: 
     form = RegistrationForm() 
     profileform = ProfileForm() 
    return render(request, 'meta/register.html', {'form': form, 'profileform': profileform, 'next': next_url}) 

然而,當我希望使用保存附加簡檔信息以下行(下面放置的線new_user = form.save()):

new_user_profile = profileform.save() 

我得到以下錯誤:

Exception Type: IntegrityError 
Exception Value: (1048, "Column 'user_id' cannot be null") 

我的配置文件模型如下:

class Profile(models.Model): 
    user = models.OneToOneField(User) 
    dob = models.DateField(max_length=8) 

    class Meta: 
     managed = True 
     db_table = 'fbf_profile' 

任何幫助將是偉大的,艾倫。

回答

3

使用這樣的外鍵時,通常會看到commit=False的保存,然後手動在模型上設置外鍵。例如,

new_user = form.save() 
profile = profileform.save(commit=False) 
if profile.user_id is None: 
    profile.user_id = new_user.id 
profile.save() 

This save() method accepts an optional commit keyword argument, which accepts either True or False . If you call save() with commit=False , then it will return an object that hasn’t yet been saved to the database. In this case, it’s up to you to call save() on the resulting model instance. This is useful if you want to do custom processing on the object before saving it, or if you want to use one of the specialized model saving options. commit is True by default.

+0

謝謝旁邊的答案的解釋。幫助老知識庫。 –

0

顯然user字段未在ProfileForm中設置。對於userOneToOneFieldProfile型號需要user_id

ProfileForm需要一個user場,你必須設定,或你必須手動設置的ProfileFormsave()功能(你將不得不重寫)的user領域。

相關問題