不知道你是否需要,但我正在使用 Flask-SQLAlchemy,我仍然是初学者,但我希望这可以帮助你基本上我创建了一个名为 state 的枚举,其值为“Active”和'Inactive',我想把这些值放在一个表单中,但我想从数据库中获取值。
我的模特这个:
class StationhasBots(db.Model):
"Many to Many table one raio station will have many functions"
__tablename__ = 'station_has_bots'
fk_radio_station_id = db.Column(db.ForeignKey('radio_station.id'), primary_key=True)
fk_bot_functions_id = db.Column(db.ForeignKey('bot_functions.id'), primary_key=True)
#Function is active or not
state = db.Column(db.Enum('Active','Inactive',name='estado'),nullable=False)
#In which time it will run
run_frequency = db.Column(db.String(STRING_LEN),nullable=False)
next_run = db.Column(db.DateTime(timezone=True),nullable=False)
#Source to fetch information
source = db.Column(db.String,nullable=False)
#path to the file that will be executed to pull info.
path = db.Column(db.String,nullable=True)
function_of_bots = db.relationship("BotsFunctions", backref=db.backref('function_from_bots'))
这是我的表格:
class AddBotForm(Form):
station = QuerySelectField(query_factory=all_stations, allow_blank=False, blank_text='- select station-')
function = QuerySelectField(query_factory=all_bot_functions, allow_blank=False, blank_text='- select function-')
#state = SelectField(choices=[('active', 'Active'), ('inactive', 'Inactive')])
state = SelectField(choices=[(g, g)for g in StationhasBots.state.property.columns[0].type.enums]) #Get the state from Station_has_Bots Table.
next_run = DurationField(description=_("Duration , in HH:MM(:SS)"))
run_frequency = HiddenField()
source = StringField()
path = StringField()
submit = SubmitField(_('Save'))
在这个表单中你可以看到,在我运行查询的状态字段中,这个查询将获得我创建数据库时创建的 Enum 调用状态。
为了呈现我刚刚在视图中执行的表单
@radio.route('/bots/add/', methods=['GET', 'POST'])
@login_required
def bot_function_add():
"""Renders the form"""
form = AddBotForm(request.form)
program = None
return render_template('radio/bot.html', program=program, form=form)
然后在模板中这样做
<h2>{{ _('Add') }} {{ _('Bot') }}</h2>
<form method="POST" action=""/>
{{ form.hidden_tag() }}
{{ render_field(form, form.station) }}
{{ render_field(form, form.function) }}
{{ render_field(form, form.next_run) }}
{{ render_field(form, form.state) }}
{{ render_field(form, form.source) }}
{{ render_field(form, form.path) }}
{{ render_field(form, form.submit) }}
</form>
我认为在你的情况下,这样的事情可能对你有用。
Type = SelectField(choices=[(g, g)for g in Recipe.type.property.columns[0].type.enums])
First g -> 保持价值(在“HTML 代码”中)
Second g -> 将呈现给用户的内容。
然后在您的 create_client_recipe.html 文件中呈现表单
你只需要做类似的事情
{{ render_field(form, form.Type) }}
我知道你的帖子已经过去六个月了,希望这可以帮助其他人。