【问题标题】:How do I map WTForms field for a db.Enum model on Flask-SQLAlchemy model?如何在 Flask-SQLAlchemy 模型上映射 db.Enum 模型的 WTForms 字段?
【发布时间】:2016-01-10 06:19:57
【问题描述】:

使用以下模型:

class Recipe(db.Model):
    __tablename__ = 'recipe'
    __searchable__ = ['description']

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), index=True, unique=True, nullable=False)
    description = db.Column(db.String(128))
    style = db.Column(db.Enum('fried', 'baked', 'roasted', 'mixed', name='cooking_style'))
    type = db.Column(db.Enum('breakfast', 'lunch', 'dinner', 'snack', 'sauce', 'bread', 'dessert', name='recipe_type'))

还有以下内容:

form = CreateRecipeForm()
return render_template('create_client_recipe.html', form=form, client=c, recipe=r)

如何在 WTForm 中将 styletype(两个 db.Enum 字段)表示为选择字段?

【问题讨论】:

    标签: python flask sqlalchemy wtforms flask-wtforms


    【解决方案1】:

    不知道你是否需要,但我正在使用 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) }}
    

    我知道你的帖子已经过去六个月了,希望这可以帮助其他人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多