如何从django formtools在wizardview中引发自定义表单无效错误

时间:2018-02-14 12:22:22

标签: django django-forms django-views django-formwizard

我正在使用django-formtools来分割注册表单。我已为验证码验证添加了Google ReCaptcha。 我希望以django UpdateView中的形式产生错误。 django form wizard中是否有任何方法

messages.error(self.request, 'Invalid reCAPTCHA. Please try again.')
return super(UpdateUserProfileView, self).form_invalid(form)

这是我的done方法

def done(self, form_list, **kwargs):
    """do_something_with_the_form_data(form_list)."""
    recaptcha_response = self.request.POST.get('g-recaptcha-response')
    url = 'https://www.google.com/recaptcha/api/siteverify'
    values = {
        'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
        'response': recaptcha_response
    }
    data = urllib.parse.urlencode(values).encode()
    req = urllib.request.Request(url, data=data)
    response = urllib.request.urlopen(req)
    result = json.loads(response.read().decode())
    ''' End reCAPTCHA validation '''

    if result['success']:
        pass
    else:
        cleaned_data = super(UserProfileWizardView, self).get_all_cleaned_data()
        messages.error(self.request, 'Invalid reCAPTCHA. Please try again.')
        # raise forms.ValidationError("Invalid reCAPTCHA. Please try again.")
        # self.add_error('organization', 'Invalid reCAPTCHA. Please try again.')
        form = self.get_form(data=self.request.POST, files=self.request.FILES)
        form.add_error('organization', 'Invalid reCAPTCHA. Please try again.')
        # context = self.get_context_data(form=form, **kwargs)
        # return self.render_to_response(context)
        return cleaned_data

    return HttpResponseRedirect('/')

0 个答案:

没有答案