将用户数据用作wtforms的SelectField中的值

发布于 2025-01-27 16:56:31 字数 670 浏览 2 评论 0原文

我想将用户数据用作SelectField中的值。我正在尝试创建用户添加到数据库中的内容的列表,然后用户可以看到他们添加的内容。因此,它应该循环浏览数据库并列出用户选择的项目。然后,用户可以查看他们列出的内容,并可以在选择中编辑Selectfield。

# Ingredients Form
ITEM_AMOUNT = [(0, "-"), (1, "1/4"), (2, "1/2"), (3, "1/3"), (4, "1/8"), (5, "1"), (6, "2"), 
(7, "3"), (8, "4"), (9, "5"), (10, "6")]

class ListForm(FlaskForm):
    item = SelectField("Amount", choices=ITEM_AMOUNT)

# CSS
{% extends 'base.html' %}
{% block content %}

<form action="/dashboard" method="Post">
{{ form.hidden_tag() }}
{% for choice in list %}
    {{ form.item(class="form-select", placeholder=dict(form.item.choices).get(form.item.data)) 
}}
{% endfor %}
{% endblock %}

I would like to use the user's data as a value in SelectField. I am trying to create a list of things the user has added to the database, then the user can see what they have added. So it should loop through the database and list the items the user has chosen. The user can then see what they have listed and be able to edit the SelectField at their choosing.

# Ingredients Form
ITEM_AMOUNT = [(0, "-"), (1, "1/4"), (2, "1/2"), (3, "1/3"), (4, "1/8"), (5, "1"), (6, "2"), 
(7, "3"), (8, "4"), (9, "5"), (10, "6")]

class ListForm(FlaskForm):
    item = SelectField("Amount", choices=ITEM_AMOUNT)

# CSS
{% extends 'base.html' %}
{% block content %}

<form action="/dashboard" method="Post">
{{ form.hidden_tag() }}
{% for choice in list %}
    {{ form.item(class="form-select", placeholder=dict(form.item.choices).get(form.item.data)) 
}}
{% endfor %}
{% endblock %}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅冕 2025-02-03 16:56:31

您可以使用烧瓶表单的init函数以以下方式从数据库中定义烧瓶表单的默认值:

class ListForm(FlaskForm):
    item = SelectField("Amount", choices=ITEM_AMOUNT)
    def __init__(self, *args, **kwargs):
       super(ListForm, self).__init__(*args, **kwargs)
       self.item.choices = *Query from database* #Value from query should be a list 
                                              of choices

You can use the flask form's init function to define default values for your flask forms from your database in the following way:

class ListForm(FlaskForm):
    item = SelectField("Amount", choices=ITEM_AMOUNT)
    def __init__(self, *args, **kwargs):
       super(ListForm, self).__init__(*args, **kwargs)
       self.item.choices = *Query from database* #Value from query should be a list 
                                              of choices
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文