Flask-SQLAlchemy: How to conditionally insert or update a row

后端 未结 2 501
我寻月下人不归
我寻月下人不归 2021-01-31 19:46

My application uses a combination of Flask, Flask-SQLAlchemy, Flask-WTF and Jinja2.

In its current incarnation, I have a settings table. The table will only have one rec

2条回答
  •  一个人的身影
    2021-01-31 20:34

    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)
    

提交回复
热议问题