美好的一天!
我'm learning Django (1.8) with class-based-views. Django itself provides an authentication module with the possibility to change the user'的密码 . 在使用 Django's PasswordChangeForm(扩展 Django's SetPasswordForm)时,我偶然发现了以下错误:
init()缺少1个必需的位置参数:'user'
当我看一下SetPasswordForm类时,我可以看到它需要一个user-object作为参数 .
def __init__(self, user, *args, **kwargs):
self.user = user
super(SetPasswordForm, self).__init__(*args, **kwargs)
What did I initially do?
首先,在我看来,我只是分配了Django的PasswordChangeForm:
class ChangePassword(LoginRequiredMixin, FormView):
template_name = 'users/reset_password.html'
form_class = PasswordChangeForm
这当然导致了错误,因为没有提供用户对象 .
So what have I attempted to solve this issue?
尝试一个:自定义表单,它继承自PasswordChangeForm并添加init方法 .
由于PasswordChangeForm没有 init 方法,我创建了一个名为MyPasswordChangeForm的新表单类,它继承自PasswordChangeForm并添加了init:
class MyPasswordChangeForm(PasswordChangeForm):
def __init__(self, request, *args, **kwargs):
super(MyPasswordChangeForm, self).__init__(request.user, *args, **kwargs)
预期结果:MyPasswordChangeForm->继承自PasswordChangeForm并在SetPasswordForm中添加init-> super init-> perform init
实际结果:super正在调用LoginRequiredMixin:
init()缺少1个必需的位置参数:'request'stack-tr l:80返回super(LoginRequiredMixin,self).dispatch(request,* args,** kwargs)
尝试“两个”:次要更改将super-> MyPasswordChangeFrom更改为super-> PasswordChangeForm
尝试三:使用mixin,但不幸的是有与上面相同的结果 .
尝试四:尚未完成,但最终选择?但必须有一种方法尽可能多地使用django的形式 .
So my question is... 有人可以提供关于如何将(经过身份验证的)用户对象传递给Django 's SetPasswordForm via Django'的PasswordChangeForm的提示或小解释,因此我可以尽可能多地使用当前存在的表单 .
提前致谢!
1 回答
初始化时,
request
默认不发送到FormView
. 你不得不以某种方式偷偷溜进去 .基于您的尝试#1,一个好方法是覆盖
FormView
中的方法get_form_kwargs()
,并添加request
作为super
已经提供的字典的键 . 然后,使用MyPasswordChangeForm
的__init__
中的kwargs
来获取request
.从根本上说,你会做以下事情:
然后,在你的Form的init中: