25

我最近在使用 FormView 时遇到了问题,发现这样做的方法是使用 get_form_kwargs。

这是我的代码:

class InternalResetPasswordView(FormView):

template_name = 'reset_password.html'
form_class = forms.InternalPasswordResetForm

# success_message = "Password was reset successfully"

# To get request object
# http://notesondjango.wordpress.com/2012/12/18/modelform-formview-and-the-request-object/
# https://stackoverflow.com/questions/13383381/show-message-after-password-change
# http://pydanny.com/simple-django-email-form-using-cbv.html
# http://bubuzzz.wordpress.com/2012/05/01/class-based-generic-views-in-django-a-simple-sample/
def get_form_kwargs(self):
    kwargs = super(InternalResetPasswordView, self).get_form_kwargs()
    kwargs['user'] = self.request.user
    return kwargs

def get_success_url(self):
    return reverse('user-detail', kwargs={'pk': self.request.user.id})

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
    return super(InternalResetPasswordView, self).dispatch(*args, **kwargs)   

'''
def get_context_data(self, **kwargs):

    context = super(InternalResetPasswordView, self).get_context_data(**kwargs)
    context['InternalPasswordResetForm'] = context.get('form')

    return context


def get_form_kwargs(self):
    kwargs = super(InternalResetPasswordView, self).get_form_kwargs()
    kwargs['request'] = self.request
    return kwargs

'''
# self.request.user method obtained from
# https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/
def form_valid(self, form):
    current_password = form.cleaned_data['old_password']
    new_password =  form.cleaned_data['new_password1']
    confirm_new_password = form.cleaned_data['new_password2']
    user = self.request.user
    if user.check_password(current_password) and new_password == confirm_new_password:
        user.set_password(new_password)
        user.save()
        # form.valid() redirects to get_success_url
    return super(InternalResetPasswordView, self).form_valid(form)

看了这篇文章后,我仍然不明白为什么必须使用 get_form_kwargs 以及为什么在这种情况下使用 self.request 而不是 self.request.user 会给出__init__() got an unexpected keyword argument 'request'

有人可以向我解释一下吗?

感谢所有的帮助:)

4

1 回答 1

30

get_form_kwargs方法将返回一个字典,其中包含将传递给__init__表单的 kwargs。现在,如果您有一个表单,它需要一个名为 kwarg 的表单并将其user传递给一个名为kwarg 的表单,request它将抱怨您看到的错误。如果你想通过request而不是user(这是我通常做的,因为请求包含用户),那么你应该像这样定义你的表单类:

类 RequestForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(RequestForm, self).__init__(*args, **kwargs)
于 2013-09-04T05:15:50.787 回答