Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

django rest framework. raise_exception=True

I'm wondering, when should I use serializer.is_valid(raise_exception=True)? If I'm not implementing any custom validation, do I need to use the raise_exeption=True flag? What if my API doesn't raise ValidationErrors, is it a bad practice? if it is, then why is the default raise_exception=False? I'm just wondering if I should set this to True. Thanks for your advice.

Upvotes: 24

Views: 19620

Answers (1)

Ramast
Ramast

Reputation: 7709

Usually when validating a serializer we do something like this

if not serializer.is_valid(): raise ValidationError(serializer.errors) restapi catch this exception and return 400 response with the provided errors in form of list or dictionary. A cleaner way for writing the code above is

serializer.is_valid(raise_exception=True)

80% of the time u will want to use raise_exception=True unless you need to handle serializer's errors in your code rather than simply telling the user his input is wrong.

Upvotes: 43

Related Questions