[Django]-How to set min length for models.TextField()?

30👍

You would use a custom validator, specifically MinLengthValidator

8👍

in this case you need to import the MinLengthValidator resource from django.core.validators, which will look like this:

from django.core.validators import MinLengthValidator

To use the resource, the model must be written as follows:

variable = models.TextField(
        validators=[
            MinLengthValidator(50, 'the field must contain at least 50 characters')
            ]
        )

6👍

When declaring a Django form

cell_phone=forms.CharField(max_length=10,min_length=10);

When rendering a form field in Django template

{% render_field form1.cell_phone  minlength="10" maxlength="10" %}

Underscore is confusing

👤Aseem

5👍

For models.Models field validation:

from django.db.models import TextField
from django.db.models.functions import Length

TextField.register_lookup(Length, 'length')

class Foo(models.Mode):
    text_field_name = models.TextField()
    
    class Meta:
        constraints = [
            models.CheckConstraint(
                check=Q(text_field_name__length__gte=10),
                name="text_field_name_min_length",
            )
        ]

Using constrains will create validation on the database level (I think), which will be called on save()
This also works for CharField.

Leave a comment