Heyho,
我使用Profile
到OnetoOneField
创建了一个模型User
。在account_settings
视图中,我希望能够更改配置文件信息或重置密码。更改配置文件信息工作正常,但当我尝试更改密码时,我的PasswordChangeForm
始终无效。有人能告诉我我的错误在哪里吗?
以下是观点:
def account_settings(request, id):
user = Profile.objects.get(id=id)
if request.method == 'POST' and 'passwordchange' in request.POST:
user_form = PasswordChangeForm(request.user, prefix='password')
if user_form.is_valid():
user_form.save()
update_session_auth_hash(request, user)
messages.success(request, 'Your password was successfully updated!')
else:
messages.error(request, 'Please correct the error below.')
return redirect('profile', user.id)
elif request.method == 'POST' and 'profilechange' in request.POST:
profile_form = ProfileForm(request.POST, instance=request.user.profile,prefix='profil')
if profile_form.is_valid():
profile_form.save()
return redirect('account_settings',user.id)
#else:
#messages.error(request, _('Please correct the error below.'))
else:
user_form = PasswordChangeForm(user=request.user, prefix='password')
profile_form = ProfileForm(instance=request.user.profile,prefix='profil')
return render(request, 'app/accountform.html', {'profileuser': user,'user_form': user_form,'profile_form': profile_form})
模板:
<div class="col-md-9">
<div class="profile-content">
<form method="post" >
{% csrf_token %}
{{ profile_form.as_p }}
<button type="submit" name="profilechange">Änderungen speichern</button>
</form>
<form method="post" >
{% csrf_token %}
{{ user_form.as_p }}
<button type="submit" name="passwordchange">Passwort ändern</button>
</form>
<a href="{% url 'profile' user.profile.id %}" type="submit" class="btn btn-default">Abbrechen</a>
</div>
</div>
答案 0 :(得分:0)
您没有将POST
数据传递给表单,这就是它无法验证的原因。初始化时需要传递POST
数据:
user_form = PasswordChangeForm(request.user, data=request.POST, prefix='password')
if user_form.is_valid():
# This should work now