Search code examples
django-rest-framework

What is the difference between django rest_framework "serializers.ValidationError" and "exceptions.ValidationError"


I was wondering, if there are any differences between django rest_framework`s:

from rest_framework.exceptions import ValidationError
from rest_framework.serializers import ValidationError

as they are imported differentrly.


Solution

  • rest_framework.exceptions.ValidationError is used for general validation errors outside of serializers,

    while rest_framework.serializers.ValidationError is used specifically for validation errors within serializer classes.

    Example of from rest_framework.exceptions import ValidationError

    def my_view(request):
        # Example validation in a view
        if not request.user.is_authenticated:
            raise ValidationError("User must be authenticated to access this endpoint")
    

    Example of from rest_framework.serializers import ValidationError

    from rest_framework import serializers
    
    class MySerializer(serializers.Serializer):
        username = serializers.CharField(max_length=100)
        email = serializers.EmailField()
    
        def validate_username(self, value):
            if len(value) < 3:
                raise serializers.ValidationError("Username must be at least 3 characters long.")
            return value