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

时间:2015-01-24 00:10:06

标签: python django user-controls django-admin

当我尝试更新用户数据时,我收到此错误:数据库正在尝试使用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',]

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

1 个答案:

答案 0 :(得分:3)

m.username = request.user

问题出在哪里,应该是:

m.username = request.user.username