dimanche 26 février 2017

Select from dropdown list in flask

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> - Test</title>
  </head>
  <body>
    <h1>Hi, !</h1>


      <h2>Option selector</h2>
        <h3><table><form action="" method="POST">
          <td>
          <label>Select :</label>
            <select name="option" width="300px">
            
            </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




Aucun commentaire:

Enregistrer un commentaire