Django TextField max_length validation for ModelFo

2019-03-09 17:54发布

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? Any help is much appreciated.

Thanks,

oMat

3条回答
闹够了就滚
2楼-- · 2019-03-09 18:01

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-09 18:03

No need to import MaxLengthValidator from validators for Django 2.x

from django.db import models
class Comment(models.Model):
  comment = models.TextField(max_length=200)
查看更多
女痞
4楼-- · 2019-03-09 18:12

You can enforce a max length for a TextField by defining a CharField with a Textarea widget like this:

class MyClass(models.Model):
    textfield = models.TextField()

class MyForm(forms.ModelForm):
    textfield = forms.CharField(
        max_length = 50,
        widget = forms.Textarea
    )

    class Meta:
        model = MyClass
        fields = ('textfield',)
查看更多
登录 后发表回答