如何打印ValidationError?

问题描述 投票:0回答:1

我有错误来自:

errors = form.errors.as_data()

并在模板中:

{% if errors %}
    {% for field, error in errors.items %}
        <div class="alert alert-danger">
            {{ field }} - {{ error }}
        </div>
    {% endfor %}
{% endif %}

但它告诉我:

first_name - [ValidationError([u'This field is required.'])]

如何获得唯一的消息?

django django-templates
1个回答
1
投票

如果要访问as_data()实例,ValidationError方法很有用。如果您只想访问错误消息,那么使用form.errors而不是form.errors.as_data()

{% if form.errors %}
    {% for field, error in form.errors.items %}
        <div class="alert alert-danger">
            {{ field }} - {{ error }}
        </div>
    {% endfor %}
{% endif %}
© www.soinside.com 2019 - 2024. All rights reserved.