在IF语句中使用request.form.get()

时间:2019-02-16 02:42:42

标签: python sqlite

我正在尝试根据用户在我的网站上选择的选项在SQlite数据库中执行“ INSERT INTO table(...)”。这是我的html(在顶部)和python(在底部)的一部分:

<form action="/calendar" method="post" autofocus name="name" placeholder="name" type="text">
        <div class="form-group">
            <select class="form-control" name="expenses">
                <option disabled selected value>Expenses</option>
                    <option value="home">home expense</option>
                    <option value="food">food expense</option>
                    <option value="child">child expense</option>
                    <option value="debt">debt expense</option>
                    <option value="healthcare">healthcare expense</option>
                    <option value="transportation">transportation expense</option>
                    <option value="personalcare">personalcare expense</option>
                    <option value="petcare">petcare expense</option>
                    <option value="entertainment">entertainment expense</option>
                    <option value="others">others expense</option>

            </select>


if request.method == "POST":
        # return apology page if anything isn't provided correctly
        note = request.form.get("note")
        amount = float(request.form.get("amount"))
        if amount < 0:
            return apology("provide positive amount")

        if request.form.get("home"):

            db.execute("INSERT INTO home (id, amount, note, date) VALUES(:id, :amount, :note, :date)", id=session["user_id"], amount=usd(amount), note=note, date=now.strftime("%Y-%m-%d %H:%M:%S"))

        elif request.form.get("food"):

            db.execute("INSERT INTO food (id, amount, note, date) VALUES(:id, :amount, :note, :date)", id=session["user_id"], amount=usd(amount), note=note, date=now.strftime("%Y-%m-%d %H:%M:%S"))

如果我不使用if语句,它将正确插入数据,但是使用if语句则不会插入数据。有人可以给我一个解释,还是给我替代的方法来使用python和SQLite datebase达到相同的结果?

1 个答案:

答案 0 :(得分:0)

没有name="home"name="food"的表单输入。这些只是<select>中名称为expenses的选项的值。您想要的是:

expenses = request.form.get("expenses")
if expenses == "home":
    db.execute("INSERT INTO home (id, amount, note, date) VALUES(:id, :amount, :note, :date)", id=session["user_id"], amount=usd(amount), note=note, date=now.strftime("%Y-%m-%d %H:%M:%S"))
elif expenses = "food":
    db.execute("INSERT INTO food (id, amount, note, date) VALUES(:id, :amount, :note, :date)", id=session["user_id"], amount=usd(amount), note=note, date=now.strftime("%Y-%m-%d %H:%M:%S"))