如何在 Django 的模型表单中制作多行 CharField?我不想使用 Textarea,因为我希望输入的长度有限。问题是关于字段“描述” 这是我的模型:
class Resource(models.Model):
type = models.CharField(max_length=50)
name = models.CharField(max_length=150)
description = models.CharField(max_length=250, blank=True)
creationDate = models.DateTimeField(default=datetime.now, blank=True)
这是我的表格:
class AddNewResourceForm(forms.ModelForm):
class Meta:
model = Resource
fields = ("name","type","description")
def __init__(self, *args, **kwargs):
super(AddNewResourceForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class' : 'new-res-name',
'placeholder' : 'max 150 characters'})
self.fields['type'].widget.attrs.update({'class' : 'new-res-type',
'placeholder' : 'max 50 characters'})
self.fields['description'].widget.attrs.update({'class' : 'new-res-
description', 'placeholder' : 'max 250 characters'})
请您参考如下方法:
我认为您应该使用 TextField,确保执行所需的限制,这可以分两步完成:
1) 在 description 字段上设置一个 max_length 属性,这将确保该限制反射(reflect)在客户端。
来自docs :
If you specify a max_length attribute, it will be reflected in the Textarea widget of the auto-generated form field. However it is not enforced at the model or database level.
2) 申请MaxLengthValidator到您的领域以确保您也有服务器端限制验证,例如
from django.core.validators import MaxLengthValidator
class Resource(models.Model):
type = models.CharField(max_length=50)
name = models.CharField(max_length=150)
description = models.TextField(max_length=250, blank=True,
validators=[MaxLengthValidator(250)])
creationDate = models.DateTimeField(default=datetime.now, blank=True)
