@@ -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