使用 cleaned_data.get("field") 会在未打印表单时导致 AttributError

Using cleaned_data.get("field") results in AttributError when form is not printed

美好的一天!

我有一个奇怪的情况,我不明白。我有一个 FormView,用户可以在其中填写用户名或电子邮件以恢复帐户密码。在视图 FormView 中,我得到以下情况:

class RecoverPassword(FormView):
    """ Request password recovery by username or email address """

    template_name = "users/recover.html"
    form_class = RecoverPasswordForm

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        print(form) # <<<--- Removing this results in an error
        username = form.cleaned_data.get("username")

        if username:
            print(username)

        return HttpResponseRedirect(self.get_success_url())

这有效,填写的用户名显示在终端中。 但是,如果我删除以下行:

print(form)

然后用用户名填写表格并点击提交,我得到以下信息 错误:

Exception Type: AttributeError
Exception Value: 'RecoverPasswordForm' object has no attribute 'cleaned_data'

我只是想不通为什么会这样。有人知道这里发生了什么吗?提前致谢!

为什么要在 post 中执行此操作?改为使用 form_valid 方法:

def form_valid(self, form):
    username = form.cleaned_data.get("username")

    if username:
        print(username)
    return HttpResponseRedirect(self.get_success_url())