Reputation:
First thing, I have started with Flask recently so I am total newbie for now, but I like it and hopefully will improve my skills later on in the process. However, there may be some very basic things that I am missing such as the following: I have created Form with selectfield included:
class AddProductForm(Form):
subcategory = SelectField('')
And afterwards I'm fetching the results from the query and applying them to the choices of the SelectField.
...
cur = conn.cursor()
cur.execute("SELECT name FROM subcategory")
subcategories = cur.fetchall()
cur.close()
form = AddProductForm(CombinedMultiDict((request.files, request.form)))
form.subcategory.choices = [(subcat, subcat) for subcat in subcategories]
...
Everything is working good so far, I got all of the results in the SelectField, but I got them returned with the name of the column too, so basically the value for each option of the select field looks formatted like this (where 'name' is the name of the column in the database:
{'name': 'Gears and bolts'}
My question - Instead of this entire previous line, is it possible to display only the value (in this case, "Gears and bolts") as an option text of the select field?
Thanks.
Upvotes: 1
Views: 869
Reputation:
I figured out, based on this answer here, and I will put the answer here just in case there is somebody in need of it. Basically, I've changed this line:
form.subcategory.choices = [(subcat, subcat) for subcat in subcategories]
to the following:
form.subcategory.choices = [(subcat, subcat['name']) for subcat in subcategories]
And damn... that was some basic stuff, man. Previously, I was trying to use subcat.name
instead of subcat['name']
, which obviously was was wrong way to access the value, and I was getting AttributeError: 'dict' object has no attribute 'name'
Upvotes: 2