【问题标题】:Questions about django form.errors, to get the raw error messages有关 django form.errors 的问题,以获取原始错误消息
【发布时间】:2014-05-01 08:26:51
【问题描述】:

django 文档说 https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.errors

访问 errors 属性以获取错误消息字典:

f.errors {'sender': ['请输入有效的电子邮件地址。'], 'subject': ['此字段为必填项。']}

但是,当我尝试打印 forms.errors 时,我得到了 html 代码。

def login(request):
    if request.method == "GET":
        return render(request, r"login.html")
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            return HttpResponse("valid")
        else:
            print form.errors
            return HttpResponse("Invalid")

Django version 1.6.4, using settings 'test_proj.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

<ul class="errorlist"><li>username<ul class="errorlist"><li>Ensure this value ha
s at most 3 characters (it has 6).</li></ul></li></ul>

例如,我需要获取原始错误以显示 ajax 消息器

response_json = {"status": "error", "content": "Username is too short"}

如果有任何其他方法可以获取原始错误消息,您也可以告诉我。谢谢!

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    这只是调用print 的人工制品:隐式转换为字符串,ErrorList 类的__str__ method 调用其as_ul 方法以输出为HTML - 这样您就可以简单地在模板中输出错误列表通过{{ form.errors }}

    对象本身的内容不是HTML,可以通过print repr(form.errors)查看。

    【讨论】:

      猜你喜欢
      • 2013-09-27
      • 2021-10-31
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 2015-10-05
      相关资源
      最近更新 更多