54👍
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.
6👍
Why don’t you use a TextField? From the manual:
For large amounts of text, use
TextField.
- [Django]-Foreign key from one app into another in Django
- [Django]-Django and postgresql schemas
- [Django]-Generating a Random Hex Color in Python
3👍
Why don’t you use ModelForm
. ModelForm enforces a validation, setting its default max_length to model field’s max_length property, and raising proper validation error when form.is_valid()
is called. That way you don’t have to save the form, until form is validated.
Or, if you want to silently pass the validation and truncate suits best to you, write a simple django form, and write a clean method that truncates input string to the max_length and return stripped data. Take data from form.cleaned_data
after form is validated and save the object.
All considering the fact, Forms are designed to validate data before going to DB.
- [Django]-How can I get all the request headers in Django?
- [Django]-Numeric for loop in Django templates
- [Django]-Django query datetime for objects older than 5 hours
-4👍
That seems inelegant and there must be a better way.
The only reason the truncate behavior ever happens in the first place is because of MySQL’s failure to adhere to the SQL Standard. The throwing of an exception is the correct response when attempting to INSERT a string into a VARCHAR field that is not wide enough to hold it. MySQL truncates and inserts instead.
If you want to silently corrupt your data, then you’ll have to do it manually somehow–PostgreSQL will never do it for you.
- [Django]-What is the difference render() and redirect() in Django?
- [Django]-How to get the value of a Django Model Field object
- [Django]-Is django prefetch_related supposed to work with GenericRelation