I throw ValidationError
while validating data in my clean
method in models.py
. How can I catch this error in my custom create
method so that it throws a json object containing the error detail in this
way
{
"detail":"input is not valid"
}
#models.py
class Comment(models.Model):
text = models.CharField(max_length=256)
commenter = models.ForeignKey(User, on_delete=models.SET_NULL)
post = models.ForeignKey(Post, on_delete=models.SET_NULL)
def clean(self, *args, **kwargs):
if containsBadWords(text):
raise ValidationError(_("Be Polite"))
#serializer.py
def create(self, validated_data):
request = self.context.get('request', None)
commenter = request.user
try:
obj = Comment.objects.create(
post = validated_data['post'],
commenter = commenter,
text = validated_data['text']
)
except ValidationError as ex:
raise ex
return obj
The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above. By default this exception results in a response with the HTTP status code "400 Bad Request".
Django Exception Classes The base class for DoesNotExist exceptions. If a query does not return any result, this exception is raised. It raises when the requested field does not exist. This exception is raised by a query if only one object is expected, but multiple objects are returned.
The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client. REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types.
Check that you have thrown serializers.ValidationError
not ValidationError
of django.core.exceptions
. You can change your create
method in this way:
def create(self, validated_data):
request = self.context.get('request', None)
commenter = request.user
try:
obj = Comment.objects.create(
post = validated_data['post'],
commenter = commenter,
text = validated_data['text']
)
except ValidationError as ex:
raise serializers.ValidationError({"detail": "input is not valid"})
return obj
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With