Home > Software engineering >  how to create 2 select fields with dependency in each other wtf_forms flask
how to create 2 select fields with dependency in each other wtf_forms flask

Time:05-17

class UpForm(FlaskForm):
    """Uploading form."""
    user_file = FileField('please upload a file',validators=[FileRequired()])
    category_1 = SelectField("main category")
    category_2 = SelectField("secondery category")
    submit = SubmitField('Submit')

this is my form it is a form for uploading files and managing them using the categories that I get from the users

  • I am new to using flask and wtf forms

first I want to know where do i write the options and how do write them for each select field?

and also I want to create dependency between the two categories so that each answer in one will give me a set of options in the second for example: cat_1->action movies -> cat_2->action1,action2,action3 cat_1->drama movies -> cat_2->drama1,drama2,drama3

how can I do that?

CodePudding user response:

I personally didn't find quite straightforward solution to this in flask. In my project I'm using method from this tutorial.

  1. create route which return jsonify
  2. create javascript onchange event which will populate second select field

All you need is in linked video.

CodePudding user response:

  1. Options can be added to a select field using this syntax

    category = SelectField(choices=[("action", "action movies"), ("drama", 'drama movies')])

  2. As for the dependency, I would say, have separate dropdowns when user selects from first dropdown then show and hide dependent dropdowns based on the selection using javascript or Jquery

    actionMovies= SelectField(choices=[("action1", "action1"), ("action2", 'action2'), ("action3", 'action3')])

    dramaMovies= SelectField(choices=[("drama1", "drama1"), ("drama2", 'drama2'), ("drama3", 'drama3)])

Here is a working example of the jquery to display dependent dropdown

  • Related