Flask WTF form not updating with the sqlite3 database

空扰寡人 提交于 2021-02-18 18:09:52

问题


I have a RadioField form item that uses values for its field from the database.

If the database is not created I cannot start the Flask Webserver even though it should only access the database when I go to that page and load that form.

If I update the database while the Webserver is running I don't see the form with the new database information.

Until I restart the Flask webserver.

How can I get it so that it forces the form to reload its values from the database when you visit the page.

Also I am pretty sure it is storing the values of the RadioField in memory since I can delete the database and the Flask Webserver will continue running and the RadioField will still be shown.

I am using a sqlite3 database and reading and writing to it with APSW(another python sqlite3 wrapper)

This is my Form

class DatabaseForm(Form):
    listOfRows = db.getDatabase()
    rows = [(str(x[0]), x) for x in listOfRows]
    images = RadioField('images', validators = [Required()], choices = rows)

Here is my View

@app.route('/database', methods = ['GET', 'POST'])
def database():
    ''' displays the database and allows the user to select an entry '''
    form = DatabaseForm()
    if form.validate_on_submit():

        primaryKey = form.images.data
        primaryKey = int(primaryKey)


        myProgram.start(primaryKey)
        return render_template('simple.html', word = "SUCCESS")
    else:
        print form.errors

    return render_template('database.html', form=form)

回答1:


You should set the field choices in the view:

    form = DatabaseForm()
    form.images.choices = [(str(x[0]), x) for x in listOfRows]
    if form.validate_on_submit():

By setting them once on the class the options are only set when the class is instantiated, so they wont reflect any changes made during the lifetime of that particular process.



来源:https://stackoverflow.com/questions/14633290/flask-wtf-form-not-updating-with-the-sqlite3-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!