Select from dropdown list in flask

17,488

You are making a pretty simple error. I'll give you some additional cleanup advice here as well. Ultimately your reference to x.option is incorrect in your Jinja syntax. Since it is a simple list you should just use x (it has no option property). Do not forget to use endfor and endif clauses.

Python:

@app.route('/')
@app.route('/index')
def index():
    user = {'name': 'Bob'}

    client = MongoClient('mongodb://localhost:27017/')
    db = client['test-database']

    collection = db.test_collection
    posts = db.posts
    name_list = [p['name'] for p in posts.find({'type': "server"})]

    return render_template("index.html",
                           title='Database selector',
                           user='Bob',
                           server_list=name_list)

Jinja/HTML:

{% for x in server_list %}
<option value="{{ x }}"{% if loop.first %} SELECTED{% endif %}>{{ x }}</option>
{% endfor %}
Share:
17,488
A.Cave
Author by

A.Cave

Updated on June 04, 2022

Comments

  • A.Cave
    A.Cave almost 2 years

    I'm very new to Flask and web development and am having some trouble with generating a list from a mongdb query and passing that through to the html template to be in a dropdown menu in Flask.

    Please see the current code below:

    views.py

    from flask import render_template
    from app import app
    from pymongo import MongoClient
    
    @app.route('/')
    @app.route('/index')
    
    def index():
    
    user = {'name': 'Bob'}
    
    client = MongoClient()
    
    client = MongoClient('mongodb://localhost:27017/')
    db = client.test_database
    db = client['test-database']
    
    collection = db.test_collection
    posts = db.posts
    name_list = []
    
    for post in posts.find({'type': "server"}):
        name_list.append(post['name'])
    
    # Get selected option and save into variable?
    #if:
    #        choice = x.option
    
    return render_template("index.html",
                           title='Database selector',
                           user = 'Bob',
                           server_list=name_list)
    

    server_list contains: [u'server1', u'server2', u'server3']

    index.html template

    <html>
      <head>
        <title>{{ title }} - Test</title>
      </head>
      <body>
        <h1>Hi, {{ user }}!</h1>
    
    
          <h2>Option selector</h2>
            <h3><table><form action="" method="POST">
              <td>
              <label>Select :</label>
                <select name="option" width="300px">
                {% for x in server_list %}
                <option value="{{ x.option }}" SELECTED>{{ x.option }}</option>
                {% endfor %}
                </select>
              </td>
    
            </form></table></h3>
    
    
      </body>
    </html>
    

    Firstly, the select list does not get populated and secondly, would anyone have a kind suggestions on how to capture the result of the selection so I can use this in another database query and generate a second dropdown list?

    Any hints greatly appreciated.

    Thank you

  • A.Cave
    A.Cave about 7 years
    Thank you PJ Santoro.. - this has been very helpful - As a continuation I would like to pass the result of the selection back to the code to make a new database query and then have that populate a second drop-down box on the same page. I have code like this for the python and jinja.. however the submitted value is not being returned correctly - would you have further thoughts please?
  • A.Cave
    A.Cave about 7 years
    if request.form['submit'] == 'myselect': choice = x sub_name_list = [q['sub_server'] for q in posts.find({'type': choice})] return render_template("index.html", title='Database selector', user='Bob', server_list=name_list, sub_server_list=sub_name_list)
  • A.Cave
    A.Cave about 7 years
    <td> <label>Select2 :</label> <select name="option" id="sub_myselect" onchange="this.form.submit()"> {% for y in sub_server_list %} <option value="{{ y }}"{% if loop.first %} SELECTED{% endif %}>{{ y }}</option> {% endfor %} </td>
  • abigperson
    abigperson about 7 years
    If you want further assistance I recommend asking a new question with a Minimal, Complete and Verifiable Example rather than inserting a bunch of code into the comments.