0

Is there a nice and clean way to use custom error codes while form validation? Eg:

{
    "name": {
        "code": 121,
        "message": "This field can't be blank."
    }
}

instead of:

{
    "name": ["This field can't be blank."]
}

Thank you.

1 Answer 1

1

You can overwrite the error message in the __init__ method of your serializer:

self.fields['field_name'].error_messages['error_message_key'] = your_custom_error

You can find all error_messages keys related to each Field in the documentation. For instance, CharFields error message keys are required, max_length, min_length.

If you're using custom field from DRF:

name = serializers.CharField(
    ...,
    error_messages={error_message_key: your_custom_error}
)

If you want to raise more specific errors, I encourage you to take a look at Raising ValidationError from the official documentation and ValidationError from DRF documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

This does not work. DRF requires string, not a dict => "AttributeError: 'dict' object has no attribute 'format'"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.