1

Working with the following model:

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'))

And the following:

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

How do I represent style & type (both db.Enum fields) as a select field in the WTForm?

1 Answer 1

4

Don't know if you need or not but I'm working with Flask-SQLAlchemy, I'm still a beginner, but I hope this can help you basically I created an Enum called state which has value 'Active' and 'Inactive', and I wanted to put this values in a form but I wanted to get the values from the database.

My model this one:

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'))    

This is my form:

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'))

In this form you can see that in the state field I run a query, this query will get the Enum called state that was created when I created the database.

To render the form I just did this in my views

@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)

And then in templates did this

  <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>

I think in your case something like this may work for you.

 Type = SelectField(choices=[(g, g)for g in Recipe.type.property.columns[0].type.enums])

First g -> Stays for value (in "HTML code")

Second g -> Is what will be presented to the user.

And then to render the form in your create_client_recipe.html file you just need to do something like

{{ render_field(form, form.Type) }}

I know that six months have past since your post hope this can help some other people.

Sign up to request clarification or add additional context in comments.

1 Comment

Many years later this answer helped me because I was having a similar issue!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.