ModelForm 的 Django TextField max_length 验证
Django 在验证 ModelForm 时不考虑 TextField 模型字段的 max_length 属性。
所以我定义了一个继承自models.TextField的LimitedTextField,并添加了类似于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)
但这仍然对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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 Django 1.2 开始,这可以通过模型级别的验证器来完成,如下所述:
https://docs.djangoproject.com/en/stable/ref/validators/
从 Django 1.7 开始,您可以使用仅在客户端强制执行的
max_length
。 参见此处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/
Since Django 1.7, you can use
max_length
which is only enforced in client side. See here您可以通过使用 Textarea 小部件定义 CharField 来强制 TextField 的最大长度,如下所示:
You can enforce a max length for a TextField by defining a CharField with a Textarea widget like this:
无需从 Django 2.x 的验证器导入 MaxLengthValidator
No need to import MaxLengthValidator from validators for Django 2.x