7

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

1 Answer 1

17

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
Sign up to request clarification or add additional context in comments.

1 Comment

we do have the validate method also, right? how can we grab authenticated user_id and validate I did search a lot but many of them used self.context['request'].user but it's totally wrong

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.