亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

post_save 在用戶和配置文件模型中具有一對一關系時導致 IntegrityError

post_save 在用戶和配置文件模型中具有一對一關系時導致 IntegrityError

catspeake 2021-07-08 18:57:23
我正在通過 onetoone 關系機智配置文件模型擴展 django 用戶模型。我想在創建用戶實例時創建用戶的配置文件,所以我使用 post_save 信號。當我創建用戶(使用注冊視圖)時,還創建了一個配置文件空白和空值,這正是我想要的。但是當我嘗試使用該用戶登錄時,會出現 IntegrityError。視圖.pydef register(request):if request.method == 'POST':    user_form = CreatUserForm(request.POST)    if user_form.is_valid():        new_user = user_form.save(commit=False)        new_user.set_password(user_form.cleaned_data['password'])        new_user.save()        return render(request,'accounts/registration_done.html',{'new_user':new_user})    else:        return render(request,'accounts/registration.html', {'user_form':user_form})else:    user_form = CreatUserForm()    return render(request,'accounts/registration.html',{'user_form':user_form})@login_requireddef edit_profile(request):if request.method == 'POST':    user_edit_form = UserEditForm(instance=request.user,data=request.POST)    profile_edit_form = ProfileEditForm(instance=request.user.profile,data=request.POST)    if user_edit_form.is_valid() and profile_edit_form.is_valid():        user_edit_form.save()        profile_edit_form.save()        messages.add_message(request,messages.SUCCESS,'profile updated')        return redirect('dashboard')    else:        return render(request,'accounts/edit_profile.html',{'user_edit_form':user_edit_form,                                                            'profile_edit_form':profile_edit_form})else:    user_edit_form = UserEditForm(instance=request.user)    profile_edit_form = ProfileEditForm(instance=request.user.profile)    return render(request,'accounts/edit_profile.html',{'user_edit_form':user_edit_form,                                                        'profile_edit_form':profile_edit_form})
查看完整描述

1 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

嘿,當您更新特定用戶實例時,將觸發后保存。


def create_user_profile(sender, instance, created, **kwargs):

      Profile.objects.get_or_create(user=instance)

或檢查實例是否是新的


def create_user_profile(sender, instance, created, **kwargs):

    if created:

      Profile.objects.create(user=instance)


查看完整回答
反對 回復 2021-07-13
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號