python - 将变量传递到 WTForms 类

标签 python flask flask-wtforms flask-login

我对 Python 和 Flask 相对缺乏经验,并且一直在尝试将变量传递给 WTForms 类。

这是我所拥有的:

views.py

@app.route('/teacher/tasks/new')
@login_required
def new_hw_task():
    classes = Class.query.filter_by(userid=current_user.userid).all()

    form = NewTaskForm(classes = classes)


    return render_template('/teacher/new_hw_task.html', form=form)

forms.py

class NewTaskForm(FlaskForm):

    classes = SelectMultipleField('Select classes to assign this homework to', choices = [("1", "Class 1"), ("2","Class 2")])

new_hw_task.html

<div class="form-group">
        {{ form.classes.label }}
        {{ form.classes(class_="form-control selectpicker", placeholder=form.classes.description, title="Select at least one class to assign", show_tick=true)}}
</div>

我想要 classes 变量(在 models.py 中定义的 Class 类的实例 - 是的,是的,我知道有多马虎它是有一个名为“Class”的类)可以在 forms.py 中访问,以便我可以用 classes 中的选项替换 SelectMultipleField 中的选项。但是,我找不到一种方法来传递它(您可以看到我尝试将 classes=classes 放入 NewTaskForm 之后的括号中)。

实际上,我更喜欢的方法是从 forms.py 中简单地访问 current_user (flask_login 设置的基于 session 的对象),但我似乎即使我在文件顶部导入 current_user ,也无法做到这一点。

有人可以向我解释一下我哪里出了问题吗?

最佳答案

SelectField 的 WTForms 文档解释如何将变量从 View 传递到表单中。就像将选项列表分配给 form.field.choices 一样简单。反过来,您可以从字段构造函数中删除 choices= 关键字参数。

根据您的情况进行调整,它看起来像这样。

@app.route('/teacher/tasks/new')
@login_required
def new_hw_task():
    classes = Class.query.filter_by(userid=current_user.userid).all()

    form = NewTaskForm()
    form.classes.choices = classes


    return render_template('/teacher/new_hw_task.html', form=form)

关于python - 将变量传递到 WTForms 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59603650/

相关文章:

python - 如何从桌面在另一个位置启动 python 脚本(带参数)

python - Flask 登录和 Heroku 问题

python - 如何使用 flask 和 wtforms 使单选字段显示默认值

Flask-Babel 转换 Flask-WTF SelectField

python - python中的字典键是RegExp

python - 处理 IncompleteRead,URLError

python - Google Calendar API 仅获取日历的第一个事件

flask - 在 Pythonanywhere 上部署 Apache Superset

python-3.x - 从 Matplotlib 填充 Flask 图像

python - 定义正确的requirements.txt文件