简体   繁体   English

多线 Charfield Django

[英]Multiline Charfield Django

How can I make a multi-line CharField in a model form in Django?如何在 Django 中以模型形式制作多行 CharField? I don't want to use Textarea, as I want the input to be with limited length.我不想使用 Textarea,因为我希望输入的长度有限。 The question is about the field 'description' This is my model:问题是关于“描述”字段 这是我的模型:

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)

And this is my form:这是我的表格:

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'})

I think that you should use the TextField , making sure to enforce the desired limit, which can be done in 2 steps:我认为您应该使用TextField ,确保强制执行所需的限制,这可以通过 2 个步骤完成:

1) Set a max_length attribute on the description field which will make sure that the limit is reflected on the client side. 1) 在description字段上设置max_length属性,这将确保限制反映在客户端。

From the docs :文档

If you specify a max_length attribute, it will be reflected in the Textarea widget of the auto-generated form field.如果您指定 max_length 属性,它将反映在自动生成的表单字段的 Textarea 小部件中。 However it is not enforced at the model or database level.但是,它不会在模型或数据库级别强制执行。

2) Apply MaxLengthValidator to your field to make sure you have a server-side limit validation as well, eg 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM