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

我们两清 提交于 2019-12-09 10:34:14

问题


I've been able to implement this change to create Field which is disabled in WTForms. How would I selectively disable a field in my view before rendering it?


回答1:


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()],
)



回答2:


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`



回答3:


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.



来源:https://stackoverflow.com/questions/16424374/python-flask-wtforms-how-can-i-disable-a-field-dynamically-in-a-view

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