如何在模板中显示Django'__ all__'表单错误?

时间:2010-03-26 18:52:20

标签: django django-forms

我有以下表单代码:

# 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__']

2 个答案:

答案 0 :(得分:104)

{{ form.non_field_errors }}

答案 1 :(得分:28)

{{ form.non_field_errors }}表示与表格不是字段相关的错误

{{ form.password.errors }}表示与文字字段相关的错误,例如在这种情况下为passoword