Nice tutorial! Very clear and complete. I wish I could create dynamic web sites with Flask without having to resort to JavaScript but you have made it quite painless. Thanks!
Great Tutorial!! Tried the lookups yesterday and failed for two hours for some reason. This tutorial showed the easy way to get it done in 5 minutes. You made my day, Many Thanks!
Not having ever seen SQLAlchemy before made understanding this video a lot harder than it needed to be. I wasn't able to recognise the difference between WTForms and SQLAlchemy. Got there in the end, though. Thanks.
Thank you bro. I was stucked . I wanted to display a list of sub categories depending on category_id. After severals hours of research, i found out that your tutorial was very helpful. I did it in a different way by passing the python CategoryArray to javascript and loop over it so i that i can grab every sub category for a related category. Thank you and good luck
Watched this video many times, still able to pull it up and get a quick solution to different scenarios involving dynamic drop downs. Keep up the flask videos !
Great tutorial! I just had one little problem. I'm using "{{ wtf.quick_form(form) }}" in the html for creating the form. And now when I submit the form, the dynamic SelectField points out the error: "Not a valid choice" for whatever value I insert. Any ideas?
Thanks so much for this great content! One question: Im trying to accomplish the same without using a database, instead simply defining a python dictionary {"CA":[("LA", "Los Angeles")] etc... It all goes pretty smooth, the event listener is reacting but it shows then all the cities in one row (inside the dropdown menu). It seems like line 38, the "cities" variable in the app.py is my problem. Because wheneverI replace my selection with the db query it all works just fine. What format/type is the "cities" variable supposed to be? Thanks so much in advance!
Thank you for video. One question, when i change state field, city field return all values merged together for ex. RenoLas Vegas as one value, can you help me please? Thanks
Hi and thanks for the great video! Everything seems to be working but i cant get the value of the state in python side. i mean that using form.state doesnt give me the value of the state.. why?
Could you do something which involves editing a form which has one field as an input field please! I am kinda stuck on it. Thanks. Otherwise, this is a great video, love it, it helped me a lot.
is this solution reusable, or at least parts of it, when using SQLAlchemy with tables connected through a foreign key? show children for certain parent? and since I've got your attention, I've got a follow up question - would it be possible to create a bidirectional link between the two select fields: show parents (for certain children, if SelectField B is picked?
PP videos are very helpful, of excellent quality delivered in an attractive low key approach. However, one gripe is use of variable names which are often confusing. In this video 'city' is used as a class and table name, with a column in table having same functional definition as the table name-with name is used as label for city column, while id could be used both in the database and in HTML as could 'name.' This makes replicating code much harder than necessary. Another video uses 'Alchemy' as a file name which one could taken as the library. Clarifying and making unique variables, file names, class names, and field names would be greatly appreciated. Explaining further how the code is working would also bring your videos to the A+ level from a B+. While it is true in practice that same word is often used for the class and the db table name in teaching this should be clarified. Finally one unanswered question is the instructor alluded to getting the State from the database instead of them being hardcoded, and as that seems problematical with a 'dependent dropdown,' it would be great to have a subsequent video on dynamic select fields showing how that could be engineered. Thank you so much Anthony---your videos do make a significant, positive contribution to the Flask Community.
I got the dynamic selectfield working with your code but whenever I store the "city" in my database it just shows 1 and not the name of the city, is there a way to show the name instead of the 1?
That was nice, but how could I get the value of a selected option, when user sending the request, I mean not the value string that show in the select input, the attribute value of the selected instead
I have a question about this. I am trying to do this dynamic implementantion of SelectField but when I submit the form I got error for "Not a valid choice". Can you explain how to do that?
hi, i tried the tutorial but i always got stuck onto the same error which is 'ValueError: too many values to unpack (expected 2)' when i tried to use the line form.city.choices=[(city.id,city.name) for city in City.query.filter_by(state='CA').all()] is there any reasons why this happened?
how would you make this so you could type in the dropdowns in case you had like 100+ values in your dropdown then you could search through them by typing
Great video man. I have a question though. How do I convert the hard coded value of "CA" in line 24 of app.py form.city.choices = [(city.id, city.name) for city in City.query.filter_by(state='CA').all()] to show only the cities in the selected state? Something like: form.city.choices = [(city.id, city.name) for city in City.query.filter_by(state=form.state.data).distinct()] I would be glad to know how to do this.
How would the chained/cascading dropdown select be implement in Flask-Admin? Can it be done without the JS being implemented in this video? Looked at a few WTForms widgets, but no success. Several answers on the net, but not able to implement the answers.
You'll have to use some kind of JavaScript to do this. I don't think there's anything that you could use out of box, because it depends on how your data is setup.
I got everything working until about 13:30, I got the alert to indicate what was selected. However, the fetch is not functioning and I keep getting the following error "'fetch' is undefined". My form is at the route "/commentSubmit", and I have made my city and state endpoint, "/commentSubmit/city/". Is it breaking because it is not the root endpoint? and if so is there a workaround?
update for anyone else who has this issue: IE does not support fetch. (use XHR instead). It also does not support "for...of" loops, so you'll need either a regular for loop or a foreach.
Can you tell me how can I use this in multiple dependent dropdown case let's say instead of just state and city let's say I want to do it for country state city towns then how can I do this I tries this method but working for only two cases that is when I select a country it's okay it show me the state of that country but when I select the state then it shows nothing and unable to go next can you tell me how can I do this or any tutorial that you want to recommend
Hi. I tried submitting the query when changing this way and was getting the response that this was not a valid choice. I am coercing an integer, but it still is not working
to clarify. Instead of using if request.method == "POST", I check if it was valid on submit. For whatever reason, it considers the dynamically created options to be "invalid". Why is that?
The error that form.errors gave me was "Not a valid choice. It would only recognize changes made by the Flask app itself (i.e. form.name.choices), not options made by the js script. I made some changes and got it to work and still validate but it is slightly more roundabout. After checking that a POST request has been made, I update the form choices on the backend as well, then check for validation.
Why do I get "RuntimeError: No application found. Either work inside a view function or push an application context. " when I try to do the query right in the Form definition?Thanks!
Since Flask is a web framework, it's assumed that everything will be run as the result of a request. If you do try to run something outside of a request (outside of a route), you will need to emulate it using with a 'with app.app_context():' block.
Hi there, i followed your tutorial to build my own dynamic select fields, but the values of the options will be referencing to my dataframe instead. However, my code does not work like yours. My Flask app keep prompting me that my code hasTypeError: Object of type int64 is not JSON serializable (referring to return jsonify({'uniqueVal' : uvArray}) ) def unique_val(col): form = Form() unique_val = [ i for i in df[col].unique() ] uvArray = [] for uv in unique_val: uvObj = {} uvObj['id'] = uv uvObj['value'] = uv uvArray.append(uvObj) return jsonify({'uniqueVal' : uvArray}) do you know what went wrong? please help a noob out thanks a ton!!
Sorry to ask but may I know how do you set up the table in the beginning? As I tried to copy the code and run, I came to an error. Please reply asap please ;-; It's for school project :'(
Copiando el codigo y googleando los errores, no logre replicar el ejemplo. Pero el codigo des esta pagina si me funciono. tutorial101.blogspot.com/2020/04/python-flask-dynamic-select-box-using.html
Join my free course on the basics of Flask-SQLAlchemy: prettyprinted.com/flasksql
The code for this video :
github.com/PrettyPrinted/dynamic_select_flask_wtf_javascript
Pro trick : watch series on flixzone. I've been using it for watching loads of movies these days.
@Kyrie Waylon Yea, I've been watching on flixzone} for years myself :)
@Kyrie Waylon Yup, have been watching on Flixzone} for years myself :D
Nice tutorial! Very clear and complete. I wish I could create dynamic web sites with Flask without having to resort to JavaScript but you have made it quite painless. Thanks!
I'm still early on in my learning and have to admit I'm a bit surprised that Flask doesn't do this.
This was so simple to follow along with. You saved me soooo much time with how clear you were in your instruction. Easiest sub I've ever made.
Great Tutorial!! Tried the lookups yesterday and failed for two hours for some reason. This tutorial showed the easy way to get it done in 5 minutes. You made my day, Many Thanks!
Really helpful!! I did implement your solution, without knowing anything about JavaScript!! Very clear
Not having ever seen SQLAlchemy before made understanding this video a lot harder than it needed to be. I wasn't able to recognise the difference between WTForms and SQLAlchemy. Got there in the end, though. Thanks.
Thank you bro. I was stucked . I wanted to display a list of sub categories depending on category_id.
After severals hours of research, i found out that your tutorial was very helpful. I did it in a different way by passing the python CategoryArray to javascript and loop over it so i that i can grab every sub category for a related category.
Thank you and good luck
Watched this video many times, still able to pull it up and get a quick solution to different scenarios involving dynamic drop downs. Keep up the flask videos !
What a incredible vídeo! Thanks for sharing this solution.
You're welcome! Thanks for watching.
This video has helped me make some code changes to make it easy and manageable. Thank you
Hi, Anthony
Thank you so much for this! It has helped me immensely!
I was just wondering where I could find the source code from this video?
Clear concise and informative. Good stuff.
Great tutorial! I just had one little problem. I'm using "{{ wtf.quick_form(form) }}" in the html for creating the form. And now when I submit the form, the dynamic SelectField points out the error: "Not a valid choice" for whatever value I insert. Any ideas?
Thank you. I was specifically looking for how to loop through a Select field from a database. This was exactly what I needed to see.
Thank you. I'm going to watch the lecture. Click subscribe. I was building a math study site and it helped.
Awesome Video. This has helped me solve my issue. Many Thanks.
hi.....lovely tutoria. Please, what if i don't want to use database? what modification will be done in the existing code? Thanks
Awesome as always. Thanks 🙂
Thanks Anthony! Very clear
That was exactly what I was looking for, thanks a lot
Professional video. Thank you very much
Much thanks, extremely clear and did exactly what I needed.
That's awesome!. You really helped me man!
thank you!
Quick question, How would I go about updating the *first* select options dynamically also? perhaps with on-click?
Thank you, very useful, clear and to point!
You're welcome! Thanks for watching.
flask-wtforms w/ sqlalchemy
see QuerySelectField documentation
Nice Video. How to display results in same page?
Thanks so much for this great content! One question: Im trying to accomplish the same without using a database, instead simply defining a python dictionary {"CA":[("LA", "Los Angeles")] etc... It all goes pretty smooth, the event listener is reacting but it shows then all the cities in one row (inside the dropdown menu). It seems like line 38, the "cities" variable in the app.py is my problem. Because wheneverI replace my selection with the db query it all works just fine. What format/type is the "cities" variable supposed to be? Thanks so much in advance!
Great video - so good.
Thank you for video. One question, when i change state field, city field return all values merged together for ex. RenoLas Vegas as one value, can you help me please? Thanks
Thanks man!
I got a question, how would it be if there were 3 fields, for example: country, state, city?
The exact same process but you'd have to check for changes to state as well.
Pretty Printed thanks
@@melosoyogui Hey did you get this example with 3 fields? If so, could you share the code?
Hi and thanks for the great video! Everything seems to be working but i cant get the value of the state in python side. i mean that using form.state doesnt give me the value of the state.. why?
Could you do something which involves editing a form which has one field as an input field please! I am kinda stuck on it. Thanks. Otherwise, this is a great video, love it, it helped me a lot.
I'll see what I can do
Very useful, thank you!
Thanks for watching!
is this solution reusable, or at least parts of it, when using SQLAlchemy with tables connected through a foreign key?
show children for certain parent?
and since I've got your attention, I've got a follow up question - would it be possible to create a bidirectional link between the two select fields:
show parents (for certain children, if SelectField B is picked?
Nice! But how do you feed the database?
Thankkkk you very much form.city.choices this is what i needed))))
💎
Kindly where is the link to this code ?
Came through again. 👍👏👏
PP videos are very helpful, of excellent quality delivered in an attractive low key approach. However, one gripe is use of variable names which are often confusing. In this video 'city' is used as a class and table name, with a column in table having same functional definition as the table name-with name is used as label for city column, while id could be used both in the database and in HTML as could 'name.' This makes replicating code much harder than necessary. Another video uses 'Alchemy' as a file name which one could taken as the library. Clarifying and making unique variables, file names, class names, and field names would be greatly appreciated. Explaining further how the code is working would also bring your videos to the A+ level from a B+. While it is true in practice that same word is often used for the class and the db table name in teaching this should be clarified. Finally one unanswered question is the instructor alluded to getting the State from the database instead of them being hardcoded, and as that seems problematical with a 'dependent dropdown,' it would be great to have a subsequent video on dynamic select fields showing how that could be engineered. Thank you so much Anthony---your videos do make a significant, positive contribution to the Flask Community.
Thanks for the feedback. I'll keep in mind what you said about the variable names.
how can I make a application like google form in flask in which I select fieldtype from drop down then enter my details according to selected option
Can you use a Postgres DB instead of sqlalchemy? Or is sqlalchemy absolutely required in order for it to interact with the javascript?
I got the dynamic selectfield working with your code but whenever I store the "city" in my database it just shows 1 and not the name of the city, is there a way to show the name instead of the 1?
got stuck there too. did you solve it?
Thanks Anthony
You're welcome! Thanks for watching.
The Flask community really owes Anthony Hebert one.
Thanks Buddy
You're welcome!
That was nice, but how could I get the value of a selected option, when user sending the request, I mean not the value string that show in the select input, the attribute value of the selected instead
Thank youuuuuuuuuuu
Can you use a Postgres DB instead of sqlalchemy?
I have a question about this. I am trying to do this dynamic implementantion of SelectField but when I submit the form I got error for "Not a valid choice". Can you explain how to do that?
Thank you
You're welcome!
hi, i tried the tutorial but i always got stuck onto the same error which is 'ValueError: too many values to unpack (expected 2)' when i tried to use the line form.city.choices=[(city.id,city.name) for city in City.query.filter_by(state='CA').all()]
is there any reasons why this happened?
Nice!
Thanks for watching.
thnak you
You're welcome!
how would you make this so you could type in the dropdowns in case you had like 100+ values in your dropdown then you could search through them by typing
Great video man. I have a question though. How do I convert the hard coded value of "CA" in line 24 of app.py
form.city.choices = [(city.id, city.name) for city in City.query.filter_by(state='CA').all()]
to show only the cities in the selected state? Something like:
form.city.choices = [(city.id, city.name) for city in City.query.filter_by(state=form.state.data).distinct()]
I would be glad to know how to do this.
How would the chained/cascading dropdown select be implement in Flask-Admin? Can it be done without the JS being implemented in this video? Looked at a few WTForms widgets, but no success. Several answers on the net, but not able to implement the answers.
You'll have to use some kind of JavaScript to do this. I don't think there's anything that you could use out of box, because it depends on how your data is setup.
at which location we have to create sqlite database? please reply as quickly as possible
You can put it in your project directory.
I got everything working until about 13:30, I got the alert to indicate what was selected. However, the fetch is not functioning and I keep getting the following error "'fetch' is undefined". My form is at the route "/commentSubmit", and I have made my city and state endpoint, "/commentSubmit/city/". Is it breaking because it is not the root endpoint? and if so is there a workaround?
update for anyone else who has this issue:
IE does not support fetch. (use XHR instead). It also does not support "for...of" loops, so you'll need either a regular for loop or a foreach.
Can you tell me how can I use this in multiple dependent dropdown case let's say instead of just state and city let's say I want to do it for country state city towns then how can I do this I tries this method but working for only two cases that is when I select a country it's okay it show me the state of that country but when I select the state then it shows nothing and unable to go next can you tell me how can I do this or any tutorial that you want to recommend
The javascript didn't work for me until I added the following above it:
Hi. I tried submitting the query when changing this way and was getting the response that this was not a valid choice. I am coercing an integer, but it still is not working
to clarify. Instead of using if request.method == "POST", I check if it was valid on submit. For whatever reason, it considers the dynamically created options to be "invalid". Why is that?
What's the exact error message you get?
The error that form.errors gave me was "Not a valid choice. It would only recognize changes made by the Flask app itself (i.e. form.name.choices), not options made by the js script. I made some changes and got it to work and still validate but it is slightly more roundabout. After checking that a POST request has been made, I update the form choices on the backend as well, then check for validation.
I encountered the same issue
I also have the same issue, and I am yet to find a working fix for my situation anywhere.
Great tutorial! But forms are still the greatest nightmare of web development!!!
Why do I get "RuntimeError: No application found. Either work inside a view function or push an application context. " when I try to do the query right in the Form definition?Thanks!
Since Flask is a web framework, it's assumed that everything will be run as the result of a request. If you do try to run something outside of a request (outside of a route), you will need to emulate it using with a 'with app.app_context():' block.
Pretty Printed Thanks a lot! I’ve got a hard time figuring out how request and app context work.
What's is jsonify???
Hi there, i followed your tutorial to build my own dynamic select fields, but the values of the options will be referencing to my dataframe instead.
However, my code does not work like yours. My Flask app keep prompting me that my code hasTypeError: Object of type int64 is not JSON serializable (referring to return jsonify({'uniqueVal' : uvArray})
)
def unique_val(col):
form = Form()
unique_val = [ i for i in df[col].unique() ]
uvArray = []
for uv in unique_val:
uvObj = {}
uvObj['id'] = uv
uvObj['value'] = uv
uvArray.append(uvObj)
return jsonify({'uniqueVal' : uvArray})
do you know what went wrong? please help a noob out thanks a ton!!
please provide source code
I'm getting this error:
Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null
Please Help!!!
It's hard to say without seeing the code. You can email me at anthony@prettyprinted.com
@@prettyprinted no problem, I solved it. Thanks for the reply.
Sorry to ask but may I know how do you set up the table in the beginning? As I tried to copy the code and run, I came to an error. Please reply asap please ;-; It's for school project :'(
Check out my basic videos on using Flask-SQLAlchemy.
Yes man. You need to set up a table and populate it
Copiando el codigo y googleando los errores, no logre replicar el ejemplo. Pero el codigo des esta pagina si me funciono. tutorial101.blogspot.com/2020/04/python-flask-dynamic-select-box-using.html
Awesome tutorial, really clear and easy to follow. Thanks so much!
Very useful, thanks a lot!
Great video. Much thanks.