我正在尝试创建编辑用户个人资料功能。但是我收到以下错误。我觉得它试图创建一个新用户而不是编辑现有用户。这可能会导致用户名不唯一。我不知道在这里要改变/添加什么。
以下是我的观点
def showProfile(request, id):
profile = DoctorSeeker.objects.get(id=id)
return render(request,'meddy1/seekerprofile.html',{'doctorSeeker': profile})
def update_profile(request):
args = {}
if request.method == 'POST':
form = UserUpdateForm(request.POST)
if form.is_valid():
form.save()
return render(request, showProfile())
else:
form = UserUpdateForm()
args['form'] = form
return render(request, 'meddy1/editseekerprofile.html', args)
这是我的表格
class UserUpdateForm(forms.ModelForm):
name = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'FirstName LastName'}))
email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Please enter a valid email address so we can reach you. No spam. Ever.'}))
password1 = forms.CharField(label="Old Password",widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Enter your password to save the changes.'}),required=False)
password2 = forms.CharField(label="New Password?",widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Only enter new password if you want to change it.'}),required=False)
password3 = forms.CharField(label="Confirm New Password",widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Confirm New Password'}),required=False)
class Meta:
model = DoctorSeeker
fields = ("name","email")
class Meta:
model = User
fields = ("password2", "password3")
def clean_password2(self):
password2 = self.cleaned_data.get("password2")
password3 = self.cleaned_data.get("password3")
if password2 and password3 and password2 != password3:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user = super(UserUpdateForm, self).save(commit=False)
user.set_password(self.cleaned_data["password2"])
fullName = self.cleaned_data["name"]
Email = self.cleaned_data["email"]
if commit:
user.save()
userProfile = DoctorSeeker(user=user, name=fullName, email=Email)
userProfile.save()
return user
答案 0 :(得分:1)
django表单的save方法将创建一个新对象(如果没有提供实例)而不是这个对象的更新。您必须先检索用户,然后首先通过表单传递实例,然后保存。
有关更多信息,请参阅:https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method