Warm tip: This article is reproduced from serverfault.com, please click

How do I get django "Data too long for column '' at row" errors to print the actual value?

发布于 2020-11-28 01:09:54

I have a Django application. Sometimes in production I get an error when uploading data that one of the values is too long. It would be very helpful for debugging if I could see which value was the one that went over the limit. Can I configure this somehow? I'm using MySQL.

It would also be nice if I could enable/disable this on a per-model or column basis so that I don't leak user data to error logs.

Questioner
Boris
Viewed
0
Melvyn 2020-11-29 05:39:58

When creating model instances from outside sources, one must take care to validate the input or have other guarantees that this data cannot violate constraints.

When not calling at least full_clean() on the model, but directly calling save, one bypasses Django's validators and will only get alerted to the problem by the database driver at which point it's harder to obtain diagnostics:


class JsonImportManager(models.Manager):
    def import(self, json_string: str) -> int:
        data_list = json.loads(json_string)  # list of objects => list of dicts
        failed = 0
        for data in data_list:
            obj = self.model(**data)
            try:
                obj.full_clean()
            except ValidationError as e:
                print(e.message_dict)  # or use better formatting function
                failed += 1
            else:
                obj.save()

        return failed

This is of course very simple, but it's a good boilerplate to get started with.