Data Truncated Errors

Published on 2009-05-06 15:03:00+00:00
Python   django   mysql   web  

I recently ran into some of the Data truncated for column ... errors in my django apps. After a little digging, I've discovered that my particular problem lie in the structure of the underlying MySQL tables. Particularly with varchar columns.

I have a model that contains a FileField:

class MyModel(models.Model):  
    file = models.FileField(upload_to="files/%Y/%m/%d")  

Note that the MySQL table generated by this model will look something like the following:

+-------------+--------------+------+-----+---------------------+----------------+  
| Field       | Type         | Null | Key | Default             | Extra          |  
+-------------+--------------+------+-----+---------------------+----------------+  
| id          | int(11)      |      | PRI | NULL                | auto_increment |  
| file        | varchar(100) |      |     |                     |                |  
+-------------+--------------+------+-----+---------------------+----------------+  

See the varchar(100)! If you're users are uploading files with long names (mine are!), this may not be enough! Note that my model also has an upload_to that includes a year, month, and day. That's already 17 characters...

So when someone tries to upload a file named:

Who_Said_One_Hundred_Characters_Would_Ever_Be_Enough_For_A_REALLY_LONG_Filename_draft_one_.docx

It will get pre-pended with '/files/2009/05/06/', and what gets stored in your table?

files/2009/05/06/Who_Said_One_Hundred_Characters_Would_Ever_Be_Enough_For_A_REALLY_LONG_Filename_draft_one_.docx

That's 112 characters... and it won't work!

The solution?
You could alter your table so that the file column is a varchar(255)... which may help.

alter table myapp_mymodel modify file varchar(255);

OR, use shorter filenames!

Good Luck!