将函数重写为类

时间:2019-05-09 21:21:54

标签: python django forms

我有一个用于更改用户密码的功能,现在我想将其重写为类视图,它给我一个错误:

__init__() missing 1 required positional argument: 'user'

功能:

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, 'Your password was successfully updated!')
            return redirect('profile')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'accounts/change_password.html', {
        'form': form
    })

到目前为止的类视图

class ChangePasswordView(FormValidMessageMixin, FormInvalidMessageMixin, FormView):
    form_class = PasswordChangeForm
    template_name = 'accounts/change_password.html'
    success_url = reverse_lazy('profile')

    def get_form_valid_message(self):
        return 'Your password was successfully updated!'

    def get_form_invalid_message(self):
        return 'Please correct the error below.'

    def form_valid(self, form):
        form.author = self.request.user
        form.save()
        return super().form_valid(form)

urls.py

path('change-password/', ChangePasswordView.as_view(), name='change-password'),

1 个答案:

答案 0 :(得分:2)

我假设您的表单需要一个参数user。因此,您需要在表单视图中覆盖get_form_kwargs()方法来传递它,如下所示:

class ChangePasswordView(FormValidMessageMixin, FormInvalidMessageMixin, FormView):
    form_class = PasswordChangeForm
    # rest of the code
    def get_form_kwargs(self, *args, **kwargs):
       form_kwargs = super().get_form_kwargs(*args, **kwargs)
       form_kwargs['user'] = self.request.user
       return form_kwargs