Auto-truncating fields at max_length in Django CharFields

You could create a custom field that auto-truncates the field (I think this code should work, but double-check it):

class TruncatingCharField(models.CharField):
    def get_prep_value(self, value):
        value = super(TruncatingCharField,self).get_prep_value(value)
        if value:
            return value[:self.max_length]
        return value

Then, instead of using models.CharField in your models.py file, you’d just use TruncatingCharField instead.

get_prep_value prepares the value for a field for insertion in the database, so it’s the ideal place to truncate.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)