How to identify the offending field in `django.db.utils.DataError: value too long for type character varying(...)`

When the error is in the log, but the data that caused it is no longer available, sometimes there’s no way of telling which field was the one that couldn’t store the longer string (when there are several fields with the same length).

Would it be possible to tweak something so the exception type django.db.utils.DataError brought this info in the message?

The underlying database, in my case, is PostgreSQL 18 with psycopg==3.3.6

As I know Django can’t reliably add the field name from this error. It exposes the underlying database exception through __cause__ (Django docs), but PostgreSQL only supplies column names for some error types (protocol docs). You can check exc.__cause__.diag.column_name with psycopg, but it may be None for this varchar error. There is a PostgreSQL request for this exact improvement: #19642.

The practical fix is to validate before writing and log the field name and length, not the value. Model.save() doesn’t call full_clean() automatically (Django docs); bulk and raw SQL write need their own validation. If you need database-side identification, named CHECK constraint can identify the failing field by constraint name, but that requires a schema changes and raises an integrity error (PostgreSQL docs). docs.djangoproject.com

1 Like

Thank you, I’ll try and implement something as you suggested.

1 Like

You can run give it a try :

from django.core.exceptions import ValidationError

try:
    obj.full_clean()
except ValidationError as exc:
    print(exc.message_dict)  # e.g. {"title": ["Ensure this value has at most 50 characters."]}
    raise

obj.save()

save() doesn’t call full_clean() automatically. This assumes your model field definitions match the database schema; bulk writes and raw SQL may need separate validation. See the Django model validation docs. docs.djangoproject.com