首页 > 解决方案 > 如何将 django 表单错误作为文本而不是 html?

问题描述

我有一个显示错误的祝酒词。

$.toast({
    text: '{{ form.non_field_errors }}'
})

但它返回的是 html 格式。所以我得到一个错误。 在此处输入图像描述

但我只想从{{ form.non_field_errors }}. 我怎么做?

标签: djangodjango-formsdjango-templates

解决方案


您可以.as_text()在以下位置使用该方法non_field_errors

$.toast({
    text: '{{ form.non_field_errors.as_text }}'
})

但是请注意,为了使其更安全,您最好将其 JSON 化,并将输出标记为安全。

因此,您最好在视图中进行一些处理:

from json import dumps as jdumps

def some_view(request):
    some_form = ModelForm(request.POST)
    errors = jdumps(some_form.non_field_errors().as_text())
    return render(request, 'some_template.html', {'errors': errors})

并在模板中将其呈现为:

$.toast({
    text: {{ errors|safe }}
})

推荐阅读