Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django TextField max_length validation for ModelForm

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?

like image 363
onurmatik Avatar asked Jul 08 '10 18:07

onurmatik


People also ask

How can you validate Django model fields?

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)

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do I display validation error in Django?

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.

How do you remove this field is required Django?

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.


1 Answers

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

like image 65
onurmatik Avatar answered Oct 02 '22 05:10

onurmatik