我正在尝试在前面创建“编辑个人资料”表单。发生的事情是我的表单(我不是100%确信)试图创建用户,而不是查找当前用户并更新其个人资料。所以我认为这就是问题所在。在这里检查了许多问题,但没有一个很清楚。我要编辑的字段是电子邮件(要检查是否已存在电子邮件),名称,用户类型和密码。
下面是forms.py的代码
class ProfileForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('full_name', 'active', 'admin','email','user_type')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(ProfileForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
# user.active = False # send confirmation email
if commit:
user.save()
return user
views.py的代码
def profile(request):
user = User.objects.filter(email = request.user)
# form = ProfileForm(user.values().first())
if request.method == 'POST' :
form = ProfileForm(request.POST)
if form.is_valid():
form.save(commit=True)
form = ProfileForm(user.values().first())
# print(user)
context = {
'object_list': user,
'form': form
}
return render(request, 'userpanel/profile.html',context)
预先感谢
答案 0 :(得分:1)
您没有将instance
参数传递给表单。没有实例,它将尝试创建新对象。应该是这样的:
form = ProfileForm(request.POST, instance=user)
此外,您无需使用以下查询用户:user = User.objects.filter(email = request.user)
。只需添加login_requred
装饰器以确保用户已通过身份验证并使用request.user
:
from django.contrib.auth.decorators import login_required
@login_required
def profile(request):
if request.method == 'POST' :
form = ProfileForm(request.POST, instance=request.user)