Jason Howard
Jason Howard

Reputation: 1586

Enforcing max_length on CharField

I'm have a CharField that has a max_length of 200 set in the model definition. I'm able to save strings of longer than 200 to an instance of this model without any error being thrown. Is there a way to enforce max_length when saving data to a CharField or is this limit only enforced on ModelForms?

Thanks!

Upvotes: 2

Views: 1669

Answers (1)

Bestasttung
Bestasttung

Reputation: 2458

Looks like it could come from your db.

The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django’s validation using MaxLengthValidator.

If you didn't add a validator, it looks like it's only checked on the db side. So maybe your db doesn't "understand" a max value, and just have a max one. Until this max, it accepts any length.

Anyway, you can control that from the application, just add to this field a MaxLengthValidator(limit_value, message=None). You'll find a description here.

Upvotes: 2

Related Questions