gpt4 book ai didi

python - save_model 方法,但数据库需要不同的关系?

转载 作者:太空宇宙 更新时间:2023-11-04 01:10:18 25 4
gpt4 key购买 nike

当我尝试更新用户数据时,出现此错误:数据库正在尝试使用 User 类型的值更新 CharField 类型的关系字段。确保设置正确的关系。

这是我的views.py:

def settings(request):
title = "Account Settings"
form = ProfileForm(request.POST or None, instance=request.user)

if request.method == 'POST':
if form.is_valid():
m = form.save(commit=False)
m.username = request.user
m.save()
return HttpResponseRedirect('/home.html')
else:
form = ProfileForm(instance=request.user)

context = {
'title': title,
'form': form
}
template = 'settings.html'
return render(request, template, context)

这是我的forms.py:

class ProfileForm(forms.ModelForm):
first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), max_length=30, required=True)
last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), max_length=30, required=True)
email = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), max_length=75, required=True)
# company = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), max_length=50, required=False)
# url = forms.URLField(widget=forms.TextInput(attrs={'class':'form-control'}), max_length=100, required=False)

class Meta:
model = User
fields = ['first_name', 'last_name', 'email',]

我不确定我做错了什么。任何帮助,将不胜感激。谢谢!

最佳答案

m.username = request.user

就是问题所在,应该是:

m.username = request.user.username

关于python - save_model 方法,但数据库需要不同的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28120799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com