Python Flask WTForms: How can I disable a field dynamically in a view?

青春壹個敷衍的年華 提交于 2019-12-03 12:20:19
fengling 姚

vim forms.py:

add_time = DateTimeField(

    '添加时间',
    format='%Y-%m-%d %H:%M:%S',
    default=datetime.datetime.now(),
    # I use bs3,and it well add input an attribute disabled
    render_kw={'disabled':''},
    validators=[DataRequired()],
)

If you're trying to remove a field you could look at the Removing Fields Per-instance in the documentation.

From the docs:

Sometimes, you create a form which has fields that aren’t useful in all circumstances or to all users. While it is indeed possible with form inheritance to define a form with exactly the fields you need, sometimes it is necessary to just tweak an existing form. Luckily, forms can have fields removed post-instantiation by using the del keyword:

class MagazineIssueForm(Form):
    title  = TextField()
    year   = IntegerField('Year')
    month  = SelectField(choices=MONTHS)

def edit_issue():
    publication = get_something_from_db()
    form = MagazineIssueForm(...)

    if publication.frequency == 'annual':
        del form.month`

It's almost as @Bibhas proposed. If I understand this correctly and you want to disable a field through the html disabled attribute, then the following worked for me:

form.field(disabled=True)

This answer might be a bit late, but if any one else has this problem it might help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!