Creating a Dynamic Select Field With Flask-WTF and JavaScript

Поділитися
Вставка
  • Опубліковано 9 лис 2024

КОМЕНТАРІ • 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

  • @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.

  • @SavoelH
    @SavoelH 2 роки тому +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.

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

  • @emanuelortiz6858
    @emanuelortiz6858 Рік тому

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

  • @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.

  • @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

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

  • @iboldness
    @iboldness 5 років тому +12

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

    • @prettyprinted
      @prettyprinted  5 років тому

      You're welcome! Thanks for watching.

  • @samgotit
    @samgotit 4 роки тому

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

  • @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?

  • @williamgeorge2045
    @williamgeorge2045 4 роки тому

    Clear concise and informative. Good stuff.

  • @joaoalencastro380
    @joaoalencastro380 5 років тому +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.

  • @onehundredplan
    @onehundredplan 3 роки тому

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

  • @andrewhadfield7754
    @andrewhadfield7754 3 роки тому

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

  • @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

  • @rangabharath4253
    @rangabharath4253 Рік тому

    Awesome as always. Thanks 🙂

  • @da_ab
    @da_ab 4 роки тому

    Thanks Anthony! Very clear

  • @Dreaming-11
    @Dreaming-11 3 роки тому

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

  • @Crimau12000
    @Crimau12000 3 роки тому

    Professional video. Thank you very much

  • @danielschmaniel7461
    @danielschmaniel7461 4 роки тому

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

  • @jecerquerac
    @jecerquerac 3 роки тому

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

  • @RaniLink
    @RaniLink 3 роки тому

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

  • @MrKonstantiniesta
    @MrKonstantiniesta 5 років тому

    Thank you, very useful, clear and to point!

    • @prettyprinted
      @prettyprinted  5 років тому

      You're welcome! Thanks for watching.

  • @stumblinzz
    @stumblinzz 5 років тому +2

    flask-wtforms w/ sqlalchemy
    see QuerySelectField documentation

  • @JainmiahSk
    @JainmiahSk 3 роки тому

    Nice Video. How to display results in same page?

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

  • @karlduckett
    @karlduckett 3 роки тому

    Great video - so good.

  • @МаркоРосић
    @МаркоРосић 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

  • @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 6 років тому +1

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

  • @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?

  • @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.

  • @renanrosa5527
    @renanrosa5527 5 років тому +2

    Very useful, thank you!

  • @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?

  • @RodrigoColpoAmarante
    @RodrigoColpoAmarante 3 роки тому

    Nice! But how do you feed the database?

  • @thegaribovv
    @thegaribovv 4 роки тому

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

  • @TheKnowledgeExpress
    @TheKnowledgeExpress 3 роки тому

    💎

  • @michaelmaina8427
    @michaelmaina8427 4 роки тому +2

    Kindly where is the link to this code ?

  • @cedrickiplimo2991
    @cedrickiplimo2991 4 роки тому

    Came through again. 👍👏👏

  • @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.

  • @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

  • @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?

  • @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 Рік тому

      got stuck there too. did you solve it?

  • @tonygharib1
    @tonygharib1 6 років тому

    Thanks Anthony

    • @prettyprinted
      @prettyprinted  6 років тому

      You're welcome! Thanks for watching.

  • @lator1941
    @lator1941 Рік тому

    The Flask community really owes Anthony Hebert one.

  • @AshutoshKumar-iy7tv
    @AshutoshKumar-iy7tv 5 років тому +1

    Thanks Buddy

  • @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

  • @sonnguyenhoang1002
    @sonnguyenhoang1002 5 років тому +1

    Thank youuuuuuuuuuu

  • @josecontreras3823
    @josecontreras3823 4 роки тому

    Can you use a Postgres DB instead of sqlalchemy?

  • @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?

  • @snelledre
    @snelledre 6 років тому

    Thank you

  • @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?

  • @janbodnar7815
    @janbodnar7815 6 років тому

    Nice!

  • @playgoods
    @playgoods 6 років тому

    thnak you

  • @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

  • @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.

  • @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.

  • @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.

  • @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.

  • @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

  • @damonweinstein9840
    @damonweinstein9840 3 роки тому

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

  • @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 6 років тому

      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.

  • @rahulhuilgol5304
    @rahulhuilgol5304 3 роки тому

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

  • @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.

  • @rinsyarifuddin8696
    @rinsyarifuddin8696 3 роки тому

    What's is jsonify???

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

  • @prashanthchandrasekar1026
    @prashanthchandrasekar1026 3 роки тому +1

    please provide source code

  • @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.

  • @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

  • @footflaps
    @footflaps Рік тому

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

  • @saz256
    @saz256 5 років тому +2

    Very useful, thanks a lot!

  • @NicholasVerkaik
    @NicholasVerkaik 3 роки тому

    Great video. Much thanks.