是否可以在django
表单验证中使用标签名称而不是字段名称。
例如,在无效的表单中,可能会出现以下错误:
"passenger_email":["This field is required."]
我怎样才能获得
"Passenger email":["This field is required."]
答案 0 :(得分:3)
您可以编写自定义异常处理程序http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
view = context['view']
response = exception_handler(exc, context)
fields = view.get_serialzer().get_fields()
details = {}
for k, v in response.data['detail'].items():
try:
field = fields[k]
label = getattr(field, 'label', '')
if label:
detail[label] = v
else:
detail[k] = v
except KeyError:
detail[k] = v
response.data['detail'] = detail
return response
答案 1 :(得分:0)
我想你是从form.errors
所以我建议你不要覆盖form.errors
但要复制它,因为你可以打破模板错误渲染。
another_errors = {form.fields[field].label: error for field, error in form.errors.items()}
我相信会这样做。