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

前端 未结 4 1390
忘掉有多难
忘掉有多难 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:36

    Similarly to the answer by @Jkk.jonah, this raises a ValidationError, but it reuses the original exception text without need to re-implement translations:

    try:
        serializer.fields['field_val1'].fail('required')
    except ValidationError as exc:
        raise ValidationError({
            'field_val1': exc.detail,
        })
    

    By default (i.e. on rest_framework.fields.Field class), available keys are:

    default_error_messages = {
        'required': _('This field is required.'),
        'null': _('This field may not be null.')
    }
    

    Subclasses can add their own error messages there (and Serializer is a subclass of Field).

    BTW, new error messages will be automagically merged with existing (inherited) messages - won't be overridden as might be expected.

提交回复
热议问题