我正在通过 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)
添加回答
举报
0/150
提交
取消