0

I'm trying to automatize updates on database since I have a lot of columns. I have succeeded to display the database using for loop, but I have problem commiting changes to database:

@app.route('/listvehicle/<int:vehicle_id>/update', methods=['GET', 'POST'])
@login_required
def update_vehicle(vehicle_id):
    vehicle = Vehicle.query.get_or_404(vehicle_id)
    form = VehicleUpdateForm() 
    if form.validate_on_submit():
        for attr,value in vehicle.__dict__.items():
            for ia in form:
                if ia == attr:
                    vehicle.__dict__[attr] = form.__dict__[ia]
        db.session.commit()
        flash(f'The user has been updated', 'success')
        return redirect(url_for('listvehicle'))
    elif request.method == 'GET':
        for attr,value in vehicle.__dict__.items():
            for ia,iv in form.__dict__.items():
                if ia == attr:
                    iv.data = value
    return render_template('updatevehicle.html', form=form)

Any help with commiting changes to database?

1
  • Are you using sqlalchemy? why are you not using a ModelForm? Commented Jan 16, 2019 at 16:53

1 Answer 1

1

I would suggest you posting the Model and Form definitions, but without seeing it, I suggest you use a different approach, changing anything with double underscores (__dict__ for example) is highly discouraged.

I see an improvement that can be made simply by using setattr and iterating over the form data:

def update_vehicle(vehicle_id):
    vehicle = Vehicle.query.get_or_404(vehicle_id)
    form = VehicleUpdateForm() 
    if form.validate_on_submit():
        for fieldname, value in form.data.items():
            setattr(vehicle, fieldname, value)
        db.session.commit()
        flash(f'The user has been updated', 'success')
        return redirect(url_for('listvehicle'))
    elif request.method == 'GET':
        for attr,value in vehicle.__dict__.items():
            for ia,iv in form.__dict__.items():
                if ia == attr:
                    iv.data = value
    return render_template('updatevehicle.html', form=form)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you a lot it works perfectly !! I don't know how the setattr() works ? Because when I look on python and try to see the attribut of my vehicle query I have an unboundField and I had no idea how to work with that
@Senseikaii setattr is the same as instance.attribute = "something", where you have the .attribute part as a variable with the name of the attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.