How to add a drop down with values(pre defined) in flask app models?

Manura Omal picture Manura Omal · Sep 5, 2017 · Viewed 7.8k times · Source

I am new to flask and I want to add drop down list to a form which has pre defined values(not taking from the DB). I created a model as follows.

class DeliveryDetails(Model):

    _tablename_ = 'deliverydetails'
    id = Column(Integer, primary_key=True)
    customer_name = Column(String(250), nullable=False)
    delivery_type = Column(String(250), nullable=False)

And view as follows.

class DeliveryDetailsView(ModelView, DeleteMixin):
    datamodel = SQLAInterface(models.DeliveryDetails)
    list_columns = ['customer_name','delivery_type']
    search_columns = ['customer_name','delivery_type']
    edit_columns = ['customer_name','delivery_type']
    add_columns = edit_columns
    label_columns = {
        'customer_name': _("Customer Name"),
        'delivery_type': _("Delivery Type") }

I want to show Air, Land, Sea as Delivery Types in a drop down list. please let me know is it possible to do as I mentioned?

Answer

Nabin picture Nabin · Sep 5, 2017

You can use WTF forms. In your WTF form use the following field:

dropdown_list = ['Air', 'Land', 'Sea'] # You can get this from your model
seqSimilarity = SelectField('Delivery Types', choices=dropdown_list, default=1)

Alternatively:

If you are using jinja template and want to do this without WTF form, then you can pass the dropdown_list as an argument in render_template(). Finally simply loop through the list and create the select in HTML.

In view file:

@app.route("/url_you_want")
def view_method():
    dropdown_list = ['Air', 'Land', 'Sea']
    return render_template('your_template.html', dropdown_list=dropdown_list)

Then in your_template.html

<select>
{% for each in dropdown_list %}
  <option value="{{each}}">{{each}}</option>
{% endfor %}
</select>