Django does not respect the max_length attribute of TextField model field while validating a ModelForm.
So I define a LimitedTextField inherited from the models.TextField and added validation bits similar to models.CharField:
from django.core import validators class LimitedTextField(models.TextField): def __init__(self, *args, **kwargs): super(LimitedTextField, self).__init__(*args, **kwargs) self.max_length = kwargs.get('max_length') if self.max_length: self.validators.append(validators.MaxLengthValidator(self.max_length)) def formfield(self, **kwargs): defaults = {'max_length': self.max_length} defaults.update(kwargs) return super(LimitedTextField, self).formfield(**defaults)
But this still has no affect on ModelForm validation.
What am I missing?
to_python() method of the models. Field subclass (obviously for that to work you must write custom fields). Possible use cases: when it is absolutely neccessary to ensure, that an empty string doesn't get written into the database (blank=False keyword argument doesn't work here, it is for form validation only)
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.
If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.
As of Django 1.2 this can be done by validators at model level, as explained here: https://docs.djangoproject.com/en/stable/ref/validators/
from django.core.validators import MaxLengthValidator class Comment(models.Model): comment = models.TextField(validators=[MaxLengthValidator(200)])
Since Django 1.7, you can use max_length
which is only enforced in client side. See here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With