django rest framework: set field-level error from serializer validate() method

前端 未结 4 1388
忘掉有多难
忘掉有多难 2021-02-02 07:08

I have a serializer that validates fields based on the values of other fields, In the error response I would like to show each field error as a field error as opposed to showing

4条回答
  •  旧巷少年郎
    2021-02-02 07:31

    I figured it out, on this page of the documentation in the "BaseSerializer" section, there's an example that shows ValidationError can take a dictionary argument upon initialization.

    If I raise ValidationError({'field_val1': ['this field is not valid']}) I get the JSON response I want.

提交回复
热议问题