当前位置:  开发笔记 > 编程语言 > 正文

如何在CreateView的form_valid方法中引发错误

如何解决《如何在CreateView的form_valid方法中引发错误》经验,为你挑选了1个好方法。

在Django项目中,我有一个视图(云),类型:CreateView.此视图具有inlineformset_factory.有用.但是,如果我提交带有错误的表单(请查看下面的"messages.error"),页面将重定向到project.get_absolute_url().问题是:表单内容回空.我知道那是因为HttpResponseRedirect.

如何在不破坏表格的情况下更改此内容?

views.py

class cloud(CreateView):
    template_name = 'base/cloud.html'
    form_class = UserForm

    def get_context_data(self, **kwargs):
        context = super(cloud, self).get_context_data(**kwargs)
        project = get_object_or_404(Project, slug=self.kwargs['slug'])
        context['project'] = project
        if self.request.POST:
            context['formset'] = IdeaFormset(self.request.POST or None)
        else:
            context['formset'] = IdeaFormset()
        return context

    def form_valid(self, form, **kwargs):
        project = get_object_or_404(Project, slug=self.kwargs['slug'])
        context = self.get_context_data()
        formset = context['formset']

        if formset.is_valid():
            self.object = form.save()
            formset.instance = self.object #IdeaFormFormSet

            nouns = project.nouns().values_list('content', flat=True)
            verbs = project.verbs().values_list('content', flat=True)
            error = False
            for form in formset.forms: #For each Idea
                form.instance.project = project
                if form.instance.sentence:
                    sentence = form.instance.sentence
                    validate_noun = [word for word in sentence.lower().split() if word in nouns]
                    validate_verbs = [word for word in sentence.lower().split() if word in verbs]

                    if (len(validate_noun) < 1):
                        error = True
                        messages.error(self.request, u'No noun was inserted into the sentence.', 'danger')

                    if (len(validate_verbs) < 1):
                        error = True
                        messages.error(self.request, u'No verb was inserted into the sentence.', 'danger')

            if not error:
                formset.save()
                messages.success(self.request, u'Success!')
            return HttpResponseRedirect( project.get_absolute_url() )

        else:
            return self.render_to_response(self.get_context_data(form=form))

cloud.html

        
{% csrf_token %} Ideas
{% for idea_form in formset %} {# Include the hidden fields #} {% for hidden in idea_form.hidden_fields %} {{ hidden }} {% endfor %}
{% for field in idea_form.visible_fields %}
{{ field.errors }} {{ field.label_tag }} {{ field }} {{ field.help_text }}
{% endfor %}
{% endfor %}
User {% for field in form %}
{{ field.label_tag }} {{ field }} {% if field.help_text %}

{{ field.help_text }}

{% endif %}
{% for error in field.errors %}{{ error }}{% endfor %}
{% endfor %} {{ formset.management_form }}

Lorenzo Peña.. 28

作为一般规则,模型验证应该进入模型字段验证器或模型的clean方法.表格验证应该采用表格cleanclean_方法.

如果你需要验证视图中的内容form_valid,你可以使用form.add_error然后,而不是重定向(或返回super(cloud, self).form_valid(form),无论如何重定向),你可以返回super(cloud, self).form_invalid(form).

检查:https: //docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.add_error



1> Lorenzo Peña..:

作为一般规则,模型验证应该进入模型字段验证器或模型的clean方法.表格验证应该采用表格cleanclean_方法.

如果你需要验证视图中的内容form_valid,你可以使用form.add_error然后,而不是重定向(或返回super(cloud, self).form_valid(form),无论如何重定向),你可以返回super(cloud, self).form_invalid(form).

检查:https: //docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.add_error


看来您在视图中还存在多个表单/表单集问题,让我建议您进一步阅读http://stackoverflow.com/questions/34251412/how-to-validate-mulitple-forms-in-一个-单一表单视图类-Django / 34275307#34275307
推荐阅读
小妖694_807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有