user3064538
user3064538

Reputation:

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

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.

Upvotes: 1

Views: 635

Answers (1)

user1600649
user1600649

Reputation:

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.

Upvotes: 1

Related Questions