Auto-truncating fields at max_length in Django CharFields

前端 未结 4 961
夕颜
夕颜 2020-12-15 16:40

I have a field that has a max_length set. When I save a model instance, and the field\'s value is greater than max_length, Django enforces that

4条回答
  •  再見小時候
    2020-12-15 17:15

    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.

提交回复
热议问题