Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise error in create method django rest framework

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
like image 216
eng.mrgh Avatar asked Sep 03 '19 17:09

eng.mrgh


People also ask

How do I increase error in Django REST Framework?

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".

How do I handle exceptions in Django?

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.

What is renderers in Django REST Framework?

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.


1 Answers

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
like image 74
eng.mrgh Avatar answered Oct 06 '22 01:10

eng.mrgh