【问题标题】:How do I display the Django '__all__' form errors in the template?如何在模板中显示 Django '__all__' 表单错误?
【发布时间】:2011-02-01 07:48:43
【问题描述】:

我的表单代码如下:

# forms.py
class SomeForm(forms.Form):
    hello = forms.CharField(max_length=40)
    world = forms.CharField(max_length=40)

    def clean(self):
        raise forms.ValidationError('Something went wrong')

# views.py
def some_view(request):
    if request.method == 'POST':
        form = SomeForm(request.POST)
        if form.is_valid():
            pass
    else:
        form = SomeForm()

    data = {
        'form': form
    }
    return render_to_response(
        'someform.html',
        data,
        context_instance=RequestContext(request)
    )

# someform.html
{{ form.hello }}
{{ form.hello.errors }}

{{ form.world }}
{{ form.world.errors }}

如何在模板级别显示来自键 __all__ 的错误,而无需在视图中单独提取它?我想避免以下情况:

    if form.errors.has_key('__all__'):
        print form.errors['__all__']

【问题讨论】:

    标签: django django-forms


    【解决方案1】:
    {{ form.non_field_errors }}
    

    【讨论】:

      【解决方案2】:

      {{ form.non_field_errors }} 与表单而非字段相关的错误

      {{ form.password.errors }} 在这种情况下与密码相关的文本字段相关的错误

      【讨论】:

        猜你喜欢
        • 2017-10-20
        • 2011-07-10
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 2014-04-09
        • 2016-04-01
        • 1970-01-01
        相关资源
        最近更新 更多