David Dahan
David Dahan

Reputation: 11162

Add a field error in Django Rest Framework validate method?

In Django Rest Framework (and Django), traditionally we check fields in validate_<field> method, and make more global checks in validate method.

However, look at this code snippet:

def validate(self, data):
    # ....
    try:
        customer.activate(data['signup_code'], data['raw_password'])
    except BadCodeProvided:
        raise ValidationError(MSG_WRONG_ACTIVATION_CODE)
    except SomeOtherException:
        raise ValidationError(SOME_OTHER_MESSAGE)

Here, I'm forced to use validatemethod because I'm using 2 fields for my validation (signup_code and raw_password). However, if an error occurs in a BadCodeProvided Exception, I know it's related to the signup_code field (and not the raw_password one) because of the exception raised here.

In the snippet code above, thiw will create a "non_field_error". Question: is there a way in DRF to raise the same error but related to the "signup_code" field? (like it would be done in a validate_signup_code method).

Thanks

Upvotes: 14

Views: 4953

Answers (1)

MaximeK
MaximeK

Reputation: 2061

you can use serializers.ValidationError in serializer :

raise serializers.ValidationError({"myField": "custom message error 1",
                               "myField2": "custom message error 1"})

doc here Validator DRF

Upvotes: 25

Related Questions