我正在尝试将 PasswordChangeForm 添加到我的项目中,但出现错误:
<块引用>"init() 缺少 1 个必需的位置参数:'user'"
我该如何解决? 我的观点:
def password_change_view(request):
if request.method == 'POST':
pass_form = PasswordChangeForm(request.POST, instance=request.user)
if pass_form.is_valid():
pass_form.save()
return redirect('users/login')
else:
pass_form = PasswordChangeForm(instance=request.user)
return render(request, 'users/change_password.html', {'password_form': pass_form})
和我的 html 文件:
{% extends 'main/layout.html' %}
{% block title %} Изменение пароля {% endblock %}
{% block content %}
<div class="user_content">
<form method="post">
{% csrf_token %}
{{ password_form.as_p }}
<center><button type="submit">Сохранить</button></center>
</form></div>
{% endblock %}
我想,我的错误在某处,但我找不到。
答案 0 :(得分:0)
PasswordChangeForm
不是 ModelForm
而是 Form
。查看它的 __init__
方法,它被声明为:
def __init__(self, user, *args, **kwargs):
...
这意味着您需要将用户作为第一个位置参数或关键字参数传递。所以你的观点应该是:
def password_change_view(request):
if request.method == 'POST':
pass_form = PasswordChangeForm(user=request.user, data=request.POST)
if pass_form.is_valid():
pass_form.save()
return redirect('users/login')
else:
pass_form = PasswordChangeForm(user=request.user)
return render(request, 'users/change_password.html', {'password_form': pass_form})