【问题标题】:How to get non_field_errors on template when using FormView and ModelForm使用 FormView 和 ModelForm 时如何在模板上获取 non_field_errors
【发布时间】:2014-08-13 19:56:42
【问题描述】:

我正在使用 FormView 和 ModelForm 来处理注册表单。如果电子邮件重复,我会提出 ValidationError。但此错误消息在注册模板上不可用,为 non_field_errors。

当我试图在 RegistrationView 中的 form_invalid 方法中查找什么是 form.errors 时,它显示了预期的错误,但不知何故它没有被传递给模板。

【问题讨论】:

  • 您需要展示模板。首先,它是non_field_errors
  • @DanielRoseman:我已经编辑过了。我发现 FormView 不应该与 ModelForm https://github.com/django/django/blob/master/django/views/generic/edit.py#L181-190 一起使用

标签: django python-2.7 django-forms django-templates django-views


【解决方案1】:

首先,我们必须确定它是非字段错误还是字段错误。

你在你定义的 ModelForm 中哪里提出了ValidationError

  1. 如果它在 Form 的 def clean() 中提出,那么它将出现在 non_field_errors 中,并且可以通过模板中的 form.non_field_errors 访问

  2. 如果它在def clean_<field_name>() 中引发,则这将是一个字段错误,可以通过模板中的form.errorsform.<field_name>.error 访问

请自行决定你想在哪里提高它。

注意:ModelForm 可以与 FormView 一起使用。但理想情况下,有 CreateView 和 UpdateView

【讨论】:

    【解决方案2】:

    这样的?

    {% if my_form.non_field_errors %}
        <div class="alert alert-error">
        <ul>
            {% for error in my_form.non_field_errors %}
                <li>{{ error }}</li>
            {% endfor %}
        </ul>
        </div>
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      相关资源
      最近更新 更多