Creating a Dynamic Select Field With Flask-WTF and JavaScript

Поделиться
HTML-код
  • Опубликовано: 27 авг 2024
  • In this video I show you how to create a dynamic (or dependent) select field using Flask-WTF and JavaScript along with the fetch function. After watching this video, you should be able to create your down drop downs that depend on others.
    Need one-on-one help with your project? I can help through my coaching program. Learn more here: prettyprinted....
    Get the code here: prettyprinted....
    Join my free course on the basics of Flask-SQLAlchemy: prettyprinted....
    Twitter: / pretty_printed
    Github: github.com/pre...

Комментарии • 116

  • @prettyprinted
    @prettyprinted  4 года назад +2

    Join my free course on the basics of Flask-SQLAlchemy: prettyprinted.com/flasksql

    • @mohammedmaamari9210
      @mohammedmaamari9210 4 года назад +3

      The code for this video :
      github.com/PrettyPrinted/dynamic_select_flask_wtf_javascript

    • @kyriewaylon823
      @kyriewaylon823 3 года назад

      Pro trick : watch series on flixzone. I've been using it for watching loads of movies these days.

    • @richardjude6150
      @richardjude6150 3 года назад

      @Kyrie Waylon Yea, I've been watching on flixzone} for years myself :)

    • @brysennico8794
      @brysennico8794 3 года назад

      @Kyrie Waylon Yup, have been watching on Flixzone} for years myself :D

  • @SavoelH
    @SavoelH Год назад +1

    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.

  • @JohnRofrano
    @JohnRofrano 5 лет назад +12

    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!

    • @seanys
      @seanys 3 года назад

      I'm still early on in my learning and have to admit I'm a bit surprised that Flask doesn't do this.

  • @BrianPip
    @BrianPip 4 года назад

    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 !

  • @emanuelortiz6858
    @emanuelortiz6858 Год назад

    Really helpful!! I did implement your solution, without knowing anything about JavaScript!! Very clear

  • @yossepbinyoum2181
    @yossepbinyoum2181 3 года назад +1

    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

  • @saschaschollmeyer9575
    @saschaschollmeyer9575 2 года назад

    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!

  • @iboldness
    @iboldness 5 лет назад +12

    What a incredible vídeo! Thanks for sharing this solution.

  • @footflaps
    @footflaps 9 месяцев назад

    Awesome tutorial, really clear and easy to follow. Thanks so much!

  • @seanys
    @seanys 3 года назад

    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.

  • @samgotit
    @samgotit 4 года назад

    This video has helped me make some code changes to make it easy and manageable. Thank you

  • @williamgeorge2045
    @williamgeorge2045 4 года назад

    Clear concise and informative. Good stuff.

  • @onehundredplan
    @onehundredplan 2 года назад

    Thank you. I'm going to watch the lecture. Click subscribe. I was building a math study site and it helped.

  • @rangabharath4253
    @rangabharath4253 Год назад

    Awesome as always. Thanks 🙂

  • @Dreaming-11
    @Dreaming-11 3 года назад

    That was exactly what I was looking for, thanks a lot

  • @JonnovanderRiet
    @JonnovanderRiet 3 года назад +6

    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?

  • @andrewhadfield7754
    @andrewhadfield7754 3 года назад

    Awesome Video. This has helped me solve my issue. Many Thanks.

  • @joaoalencastro380
    @joaoalencastro380 4 года назад +7

    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?

  • @simpletechtips8442
    @simpletechtips8442 3 года назад

    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.

  • @lator1941
    @lator1941 Год назад

    The Flask community really owes Anthony Hebert one.

  • @da_ab
    @da_ab 4 года назад

    Thanks Anthony! Very clear

  • @danielschmaniel7461
    @danielschmaniel7461 4 года назад

    Much thanks, extremely clear and did exactly what I needed.

  • @saz256
    @saz256 4 года назад +2

    Very useful, thanks a lot!

  • @jecerquerac
    @jecerquerac 3 года назад

    That's awesome!. You really helped me man!

  • @Crimau12000
    @Crimau12000 3 года назад

    Professional video. Thank you very much

  • @stumblinzz
    @stumblinzz 5 лет назад +2

    flask-wtforms w/ sqlalchemy
    see QuerySelectField documentation

  • @MrKonstantiniesta
    @MrKonstantiniesta 5 лет назад

    Thank you, very useful, clear and to point!

  • @michaelmaina8427
    @michaelmaina8427 4 года назад +2

    Kindly where is the link to this code ?

  • @lloydbalogun
    @lloydbalogun 4 года назад +1

    hi.....lovely tutoria. Please, what if i don't want to use database? what modification will be done in the existing code? Thanks

  • @NicholasVerkaik
    @NicholasVerkaik 3 года назад

    Great video. Much thanks.

  • @karlduckett
    @karlduckett 3 года назад

    Great video - so good.

  • @AbhishekYadav-mv9nk
    @AbhishekYadav-mv9nk 5 лет назад +2

    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

  • @Vanquish69
    @Vanquish69 2 года назад +1

    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?

    • @kostor222
      @kostor222 10 месяцев назад

      got stuck there too. did you solve it?

  • @calceta888
    @calceta888 Год назад

    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

  • @atrocitus777
    @atrocitus777 Год назад

    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

  • @cedrickiplimo2991
    @cedrickiplimo2991 3 года назад

    Came through again. 👍👏👏

  • @sourav9135
    @sourav9135 2 года назад

    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

  • @user-lu4de1do2i
    @user-lu4de1do2i 4 года назад +1

    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

  • @ldariva
    @ldariva 2 года назад

    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?

  • @irvinwatkins2055
    @irvinwatkins2055 5 лет назад +1

    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.

    • @prettyprinted
      @prettyprinted  5 лет назад

      Thanks for the feedback. I'll keep in mind what you said about the variable names.

  • @MichaelElimu
    @MichaelElimu 4 года назад

    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.

  • @melosoyogui
    @melosoyogui 6 лет назад +2

    Thanks man!
    I got a question, how would it be if there were 3 fields, for example: country, state, city?

    • @prettyprinted
      @prettyprinted  6 лет назад +2

      The exact same process but you'd have to check for changes to state as well.

    • @melosoyogui
      @melosoyogui 6 лет назад +1

      Pretty Printed thanks

    • @juliadills7952
      @juliadills7952 5 лет назад +1

      @@melosoyogui Hey did you get this example with 3 fields? If so, could you share the code?

  • @vaneakatok
    @vaneakatok 5 лет назад +1

    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?

  • @perfect2468
    @perfect2468 3 года назад

    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?

  • @veronicamashari8888
    @veronicamashari8888 5 лет назад +1

    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?

  • @RaniLink
    @RaniLink 3 года назад

    thank you!
    Quick question, How would I go about updating the *first* select options dynamically also? perhaps with on-click?

  • @tomaszkowalczyk5561
    @tomaszkowalczyk5561 4 года назад +1

    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!

  • @RazaAshai
    @RazaAshai 6 лет назад +2

    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

    • @RazaAshai
      @RazaAshai 6 лет назад

      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?

    • @prettyprinted
      @prettyprinted  6 лет назад +1

      What's the exact error message you get?

    • @RazaAshai
      @RazaAshai 6 лет назад +2

      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.

    • @idofxeno
      @idofxeno 5 лет назад

      I encountered the same issue

    • @dr_ari_gami
      @dr_ari_gami 5 лет назад

      I also have the same issue, and I am yet to find a working fix for my situation anywhere.

  • @JainmiahSk
    @JainmiahSk 3 года назад

    Nice Video. How to display results in same page?

  • @samuelnde9917
    @samuelnde9917 5 лет назад +3

    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.

  • @josecontreras3823
    @josecontreras3823 4 года назад

    Can you use a Postgres DB instead of sqlalchemy? Or is sqlalchemy absolutely required in order for it to interact with the javascript?

  • @matthew-donaldsangster2265
    @matthew-donaldsangster2265 4 года назад

    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?

    • @matthew-donaldsangster2265
      @matthew-donaldsangster2265 4 года назад

      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.

  • @thegaribovv
    @thegaribovv 3 года назад

    Thankkkk you very much form.city.choices this is what i needed))))

  • @tonygharib1
    @tonygharib1 6 лет назад

    Thanks Anthony

  • @RodrigoColpoAmarante
    @RodrigoColpoAmarante 3 года назад

    Nice! But how do you feed the database?

  • @mistersleyd7886
    @mistersleyd7886 4 года назад

    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.

    • @prettyprinted
      @prettyprinted  4 года назад

      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.

  • @rinsyarifuddin8696
    @rinsyarifuddin8696 3 года назад

    What's is jsonify???

  • @leanhhao86
    @leanhhao86 6 лет назад

    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!

    • @prettyprinted
      @prettyprinted  6 лет назад +1

      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.

    • @leanhhao86
      @leanhhao86 6 лет назад

      Pretty Printed Thanks a lot! I’ve got a hard time figuring out how request and app context work.

  • @josecontreras3823
    @josecontreras3823 4 года назад

    Can you use a Postgres DB instead of sqlalchemy?

  • @AshutoshKumar-iy7tv
    @AshutoshKumar-iy7tv 5 лет назад +1

    Thanks Buddy

  • @prashanthchandrasekar1026
    @prashanthchandrasekar1026 3 года назад +1

    please provide source code

  • @damonweinstein9840
    @damonweinstein9840 3 года назад

    The javascript didn't work for me until I added the following above it:

  • @sonnguyenhoang1002
    @sonnguyenhoang1002 4 года назад +1

    Thank youuuuuuuuuuu

  • @malavtreasurer
    @malavtreasurer 5 лет назад

    at which location we have to create sqlite database? please reply as quickly as possible

    • @prettyprinted
      @prettyprinted  5 лет назад +1

      You can put it in your project directory.

  • @rishitkurup2298
    @rishitkurup2298 5 лет назад

    I'm getting this error:
    Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null
    Please Help!!!

    • @prettyprinted
      @prettyprinted  5 лет назад +1

      It's hard to say without seeing the code. You can email me at anthony@prettyprinted.com

    • @rishitkurup2298
      @rishitkurup2298 5 лет назад +1

      @@prettyprinted no problem, I solved it. Thanks for the reply.

  • @snelledre
    @snelledre 6 лет назад

    Thank you

  • @soonhangchye3621
    @soonhangchye3621 5 лет назад

    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!!

  • @playgoods
    @playgoods 6 лет назад

    thnak you

  • @TheKnowledgeExpress
    @TheKnowledgeExpress 3 года назад

    💎

  • @rahulhuilgol5304
    @rahulhuilgol5304 3 года назад

    Great tutorial! But forms are still the greatest nightmare of web development!!!

  • @janbodnar7815
    @janbodnar7815 6 лет назад

    Nice!

  • @junwei2001
    @junwei2001 5 лет назад

    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 :'(

    • @prettyprinted
      @prettyprinted  5 лет назад

      Check out my basic videos on using Flask-SQLAlchemy.

    • @samuelnde9917
      @samuelnde9917 5 лет назад

      Yes man. You need to set up a table and populate it

  • @mauroezequielbravo
    @mauroezequielbravo 2 года назад

    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

  • @renanrosa5527
    @renanrosa5527 5 лет назад +2

    Very useful, thank you!