Django表单验证:以JSON格式获取错误

时间:2022-10-24 10:25:16

I have this very simple Django form

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

from django import forms

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

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).

我手动管理它,不使用模板引擎。相反,我使用ajax POST发送数据,并期望收到返回验证错误。当我使用其他框架时,我曾经在键值对中接收JSON格式的验证错误(键是带有错误的字段的名称,值是错误消息)。

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

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.

我试图在Django中实现相同的结果,但我不明白如何访问原始错误消息(相对于单个字段)并本地化它们。

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?

form.errors提供对HTML代码的访问(如下所述:显示ModelForms的django表单验证错误)。我不需要那个。我更喜欢像form.Username.validationError这样的东西:这样的东西存在吗?

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.

如果是,另外我还想知道验证错误消息是否自动转换为用户语言,如果不是,则最好的方法。

2 个解决方案

#1


5  

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().

Django 1.7允许您将表单错误发送为Json。您只需要使用以下形式的错误:form.errors.as_json()。

A great addition to the library I must say.

我必须说,这是对图书馆的一个很好的补充。

#2


3  

#from django.http import JsonResponse    

return JsonResponse({'success': False,
                      'errors': [(k, v[0]) for k, v in form.errors.items()]})

#1


5  

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().

Django 1.7允许您将表单错误发送为Json。您只需要使用以下形式的错误:form.errors.as_json()。

A great addition to the library I must say.

我必须说,这是对图书馆的一个很好的补充。

#2


3  

#from django.http import JsonResponse    

return JsonResponse({'success': False,
                      'errors': [(k, v[0]) for k, v in form.errors.items()]})