Skip to content

Commit 14d4245

Browse files
committed
fix(exceptions): 正确处理非字段错误的对象路径
修改 _flatten_errors 函数,当遇到 NON_FIELD_ERRORS_KEY 时不再将键名加入路径,使对象级错误能正确映射到父对象路径。这便于前端直接在对应对象/区域显示这些错误。
1 parent 759f678 commit 14d4245

1 file changed

Lines changed: 15 additions & 3 deletions

File tree

rest_framework/exceptions.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,20 @@ def _flatten_errors(detail, parent_path=None):
7979
- message: The error message
8080
- code: The error code
8181
82+
Object-level errors (under NON_FIELD_ERRORS_KEY) are mapped to the parent
83+
object's path, not including the non_field_errors key. This allows frontends
84+
to display these errors directly on the corresponding object/section.
85+
8286
Example:
83-
Input: {'nested': {'field': ['error1', 'error2']}}
87+
Input: {'nested': {'field': ['error1', 'error2'], 'non_field_errors': ['object error']}}
8488
Output: [
8589
{'field_path': 'nested.field', 'message': 'error1', 'code': 'invalid'},
86-
{'field_path': 'nested.field', 'message': 'error2', 'code': 'invalid'}
90+
{'field_path': 'nested.field', 'message': 'error2', 'code': 'invalid'},
91+
{'field_path': 'nested', 'message': 'object error', 'code': 'invalid'}
8792
]
8893
"""
94+
from rest_framework.settings import api_settings
95+
8996
if parent_path is None:
9097
parent_path = []
9198

@@ -109,7 +116,12 @@ def _flatten_errors(detail, parent_path=None):
109116
})
110117
elif isinstance(detail, dict):
111118
for key, value in detail.items():
112-
errors.extend(_flatten_errors(value, parent_path + [key]))
119+
# For non-field errors, use the parent path (pointing to the object itself)
120+
# instead of appending 'non_field_errors' to the path
121+
if key == api_settings.NON_FIELD_ERRORS_KEY:
122+
errors.extend(_flatten_errors(value, parent_path))
123+
else:
124+
errors.extend(_flatten_errors(value, parent_path + [key]))
113125
elif isinstance(detail, ErrorDetail):
114126
errors.append({
115127
'field_path': _get_field_path(parent_path),

0 commit comments

Comments
 (0)