Flask-SQLAlchemy: How to conditionally insert or update a row
Once your form is validated etc,
To add a new record:
new_provider = Provider(form.rssfeed.data)db.session.add(new_provider)db.session.commit()
To update an existing record:
existing_provider = Provider.query.get(1) # or whatever# update the rssfeed columnexisting_provider.rssfeed = form.rssfeed.datadb.session.commit()
The trick in updating is that you just have to change the particular field and do a commit. rest is taken care by the db session. I think you are using the merge function which is now deprecated in SQLAlchemy.
I have managed to solve the problem doing these changes to the view.py file:
@app.route('/settings', methods=["GET","POST"])def settings(): """ show settings """ provider = Provider.query.get(1) form = SettingsForm(request.form,obj=provider) if request.method == "POST" and form.validate(): if provider: provider.rssfeed = form.rssfeed.data db.session.merge(provider) db.session.commit() flash("Settings changed") return redirect(url_for("index")) else: provider = Provider(form.rssfeed.data) db.session.add(provider) db.session.commit() flash("Settings added") return redirect(url_for("index")) return render_template("settings.html", form=form)