1
votes

So I am trying to add a select field that is dynamic and gets its data from a json file.

class CreateDelivery(FlaskForm):
    manufacturer = SelectField("Manufacturer", coerce=str)

    def manu_list(self):
        with open("manufacturers.json", "r") as file:
            manu = json.load(file)
            form = CreateDelivery()
            form.manufacturer.choices = [(i['name'], i['data']) for i in manu['manufacturers']]

I looked at the docs and wrote this after reading it but I am still not getting any data in the Field. What am I missing to get the data in?

1
How are you calling the manu_list function? I assume you are using this example wtforms.readthedocs.io/en/2.2.1/fields/… Notice how the edit_user function is not part of the UserDetails form class. - gla3dr
Ok. I see. How would I go about calling it? Would it be called from within the class CreateDelivery or would I call it from its route? - Evan M
Your comment got me thinking about it differently and as such I was able to get it to work. So I moved it to the route and used the form that was being created in my route as the form to be edited. - Evan M
I encourage you to post an answer detailing how you solved your issue! - gla3dr
OK. Ill write one up! - Evan M

1 Answers

2
votes

After a comment from gla3dr, I re-looked at the docs. So I then proceed trying different methods of calling the function until I tried placing it into my routes.py file and taking the dorm that is made in the route and passing it through to the function. Low and Behold it worked. I cleaned it up and it looks like this.

@app.route("/create", methods=['GET', 'POST'])
def create():
    form = CreateDelivery() 
    with open("..\manufacturers.json", "r") as file:
            manu = json.load(file)
            form.manufacturer.choices = [(i['data'], i['name']) for i in manu['manufacturers']]

This is how I am making dynamic SelectFields by importing data from a json file.