Django表单验证:获取JSON格式的错误 [英] Django form validation: get errors in JSON format

查看:147
本文介绍了Django表单验证:获取JSON格式的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个非常简单的Django表单

I have this very simple Django form

from django import forms

class RegistrationForm(forms.Form):
    Username = forms.CharField()
    Password = forms.CharField()

我手动进行管理,不使用模板引擎.而是,我使用ajax POST发送数据,并期望接收回验证错误.在使用其他框架时,我曾经以键值对的形式接收JSON格式的验证错误(键是具有错误的字段的名称,而值是错误消息).

I manage this manually and don't use the template engine. Rather, I send data with ajax POST and expect to receive back validation errors. While I was working with other frameworks, I used to receive validation errors in JSON format in key-value pairs (the key being the name of the field with the error and the value being the error message).

{
  Username: "This field is required.",
  Password: "This field is required.",
}

我正在尝试在Django中获得相同的结果,但是我不明白如何访问原始错误消息(相对于单个字段)并将其本地化.

I'm trying to achieve the same result in Django, but I don't understand how can I access the raw error messages (relative to a single field) and localize them.

form.errors允许访问HTML代码(如此处所述:显示Django表单验证错误).我不需要那个我希望使用类似form.Username.validationError的东西:是否存在这样的东西?

form.errors give access to HTML code (as explained here: displaying django form validation errors for ModelForms). I don't need that. I'd prefer something like form.Username.validationError: does such a thing exists?

如果是,此外,我还想知道是否将验证错误消息自动翻译成用户语言,如果不是,则是执行此操作的最佳方法.

If yes, additionally I'd also like to know if the validation error message is automatically translated into the user language and, if not, the best way to do that.

推荐答案

Django 1.7可让您发送

Django 1.7 let you send the forms errors as Json. You only need to use the errors in the following form form.errors.as_json().

我必须说,这是对图书馆的一大补充.

A great addition to the library I must say.

这篇关于Django表单验证:获取JSON格式的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆