【问题标题】:Django use Widget to Override ModelForm AttributesDjango 使用 Widget 覆盖 ModelForm 属性
【发布时间】:2015-03-15 18:31:33
【问题描述】:

我有一个最大长度为 300 的标签 CharField,但我需要为默认输入保留 100 个字符,但我希望用户能够通过输入文本框设置剩余的 200 个字符。我这样做的方法是将模型中 charfield 的最大长度设置为 300,并在我的表单中为输入创建一个小部件,将用户的输入限制为 200 个字符。

但是,我做了一些测试,发现我无法从字符域本身的最大长度更改输入字段的最大长度。有谁知道这是怎么做的吗?

models.py

class Video(models.Model):
    title = models.CharField(max_length=50)
    tags = models.CharField(max_length=200)

form.py

class VideoForm(forms.ModelForm):

class Meta:
    model=Video
    fields=['title','description','authorId','tags','video','thumbnail']
    #a widget is django's representation of an html input element
    widgets = {
        'tags': forms.Textarea(attrs={'cols': 80, 'rows': 20,'maxlength':5}),
    }

上述代码生成的 html textarea 是 <textarea cols="80" id="id_tags" maxlength="200" name="tags" rows="20"></textarea>,但我希望 maxlength 为 5。

【问题讨论】:

    标签: python django forms widget maxlength


    【解决方案1】:

    重写 VideoForm 的构造函数:

    class VideoForm(forms.ModelForm):
        ...
        def __init__(self, *args, **kwargs):
            super(VideoForm, self).__init__(*args, **kwargs)
            self.fields['tags'].widget.attrs['maxlength'] = 5
    

    【讨论】:

    • 感谢您的回复,我选择了这个作为答案,但我没有自己测试过,因为我通过将 CharField 变成文本字段(所以我不必指定最大长度),然后使用小部件设置最大长度。
    猜你喜欢
    • 2016-03-20
    • 2012-10-17
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 2012-01-31
    • 2018-02-01
    • 1970-01-01
    • 2018-04-01
    相关资源
    最近更新 更多