我在尝试访问Django中的PasswordChangeView时遇到TypeError。错误是:
Django Version: 1.7.3
Exception Type: TypeError
Exception Value:
__init__() missing 1 required positional argument: 'user'
Exception Location: /usr/local/lib/python3.4/dist-packages/django/views/generic/edit.py in get_form, line 45
Python Executable: /usr/bin/python3.4
我无法找到从https://docs.djangoproject.com/en/1.7/_modules/django/contrib/auth/forms/#PasswordChangeForm加载提供的PasswordChangeForm的FormView示例
这就是我尝试这样做的方法,但即使经过一些调整,我仍然会遇到错误。
urls.py
url(r'^password/change/$', login_required(views.PasswordChangeView.as_view()), name='change_password'),
views.py
class PasswordChangeView(FormView):
template_name = 'change_password.html'
form_class = PasswordChangeForm
def dispatch(self, request, *args, **kwargs):
try:
self.initial['user'] = self.request.user
except AttributeError:
raise Http404
return super(PasswordChangeView, self).dispatch(request, *args, **kwargs)
我不确定为什么我仍然会收到此错误。如果我查看使用FormView扩展的FormMixin,我会看到以下内容:
def get_form(self, form_class):
"""
Returns an instance of the form to be used in this view.
"""
return form_class(**self.get_form_kwargs())
def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = {
'initial': self.get_initial(),
'prefix': self.get_prefix(),
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
return kwargs
和......
def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
return self.initial.copy()
来源:https://github.com/django/django/blob/master/django/views/generic/edit.py
我通过调用self.get_form_kwargs()确认self.initial包含用户:
{'initial': {'user': <SimpleLazyObject: <User: maaack>>}, 'prefix': None}
我应该如何将用户传递到表单中?
答案 0 :(得分:5)
您应该将用户作为第一个参数传递给表单构造函数。看看SetPasswordForm.__init__():
def get_form(self, form_class):
return form_class(self.request.user, **self.get_form_kwargs())
user
中没有PasswordChangeForm
字段,因此user
中的initial
密钥无用。