luishengjie
luishengjie

Reputation: 187

Submitting edited Prepopulate Flask-WTForm data from database

I would like to pre-populate my form with data from my database to make necessary changes and modify my database with these changes.enter image description here However when i run the following code below, when the form.validate_on_submit() method is initialised, the form's data is the pre-populated data from the database and not the edited version. How do i access the edited value of the form data?

@auth.route('/edit_projects', methods=['GET', 'POST'])
@auth.route('/edit_projects/<project>', methods=['GET', 'POST'])
@login_required
def edit_projects(project=None):
    form = ProjectForm()
    project_db = Project.query.all()
    edit_project_db = Project.query.filter_by(id=project).first()
    if project != None: 
        form.name.data=edit_project_db.name
        form.project_brief.data=edit_project_db.project_brief
        form.project_description.data=edit_project_db.project_description

    if form.validate_on_submit():
        edit_project_db.name = form.name.data
        edit_project_db.project_brief = form.project_brief.data
        edit_project_db.project_description = form.project_description.data
        db.session.commit()
        flash('Product %s updated.' %(str(form.name.data)))

Upvotes: 0

Views: 672

Answers (1)

ciacicode
ciacicode

Reputation: 708

I think it could help to distinguish between 'GET' and 'POST', on 'GET' you prepopulate the fields, but on 'POST' you want to see if the user has actually edited the form content.

I would split the code like:

if request.method == 'GET':
    # prepopulate
    if project != None: 
        form.name.data=edit_project_db.name
        form.project_brief.data=edit_project_db.project_brief
elif request.method == 'POST':
    # check form validates
    if form.validate_on_submit():
       # keep the rest as it is
        ...

Hope this offers some help.

Upvotes: 1

Related Questions