Raising ValidationError causes 500 Internal Server Error response

Here’s a simplified example. I have a views.py with:

# Obviously, this is used as a handler for a route in urls.py
def handle_foo(request: HttpRequest, **kwargs: dict[str, Any]) -> HttpResponse:
  txt = do_something(json.loads(request.body.decode('utf-8'))['field_i_want'])
  return JsonResponse({'ok': txt})

And I have do_something defined as:

def do_something(value: str):
  if value == 'bad': raise ValidationError('bad value')
  return f'good value: {value}'

Now I expect this to respond with a 400 Bad Request, but it responds with 500 Internal Server Error. And the traceback points to this function in Django Core: django/django/core/handlers/exception.py at ecd3071dac9bc32028849b1563dc30e49744950e · django/django · GitHub

It seems like this function is supposed to handle Django exceptions, so I’m wondering why it doesn’t handle the ValidationError?

Please post the complete error with the traceback message.

Maybe it’s too late but nevertheless.
I just came across the same error and found that I was using ValidationError from rest_framework.exceptions instead of ValidationError from django.core.exceptions.

There is even a note for former

# The recommended style for using `ValidationError` is to keep it namespaced
# under `serializers`, in order to minimize potential confusion with Django's
# built in `ValidationError`. For example:
#
# from rest_framework import serializers
# raise serializers.ValidationError('Value was invalid')