首页 > 解决方案 > 在 Flask-SQLAlchemy 中更新表 - 访问不正确的表 ID

问题描述

我正在尝试更新 Flask 中的库存项目表。我有一个更新按钮,它会显示一个带有表单的模式,您可以在其中编辑该表行和对象的特定属性。但是,它没有访问与我使用更新按钮选择的行相对应的正确表 ID。

我尝试通过在 update_item() 中打印项目属性来进行调试,以检查我是否选择了正确的项目,但似乎每次都在选择表的第一项。

这是我的views.py:

@views.route('/update_item', methods=['GET','POST'])
@login_required
def update_item():
    if request.method == "POST":
        item = Inventory.query.get(request.form.get('item_id'))
        print(item.__dict__)
        for key, value in request.form.items():
            if value:
                setattr(item, key, value)
        db.session.commit()
        print(item.__dict__)
    
    return render_template("home.html", user=current_user)

这是我的models.py:

class Inventory(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    brand = db.Column(db.String(100))
    name = db.Column(db.String(1000))
    size = db.Column(db.String(100))
    date = db.Column(db.DateTime(timezone=True), default=func.now())
    price = db.Column(db.Float(2))
    shipping_status = db.Column(db.String(200))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    fullName = db.Column(db.String(150))
    inventory = db.relationship('Inventory')

这是我的 home.html:

{% extends "base.html" %}
{% block title %}Dashboard{% endblock %}
{% block content %}
<h1>Hi {{user.fullName}}! </h1>
<h2>Here is your updated inventory.</h2>
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addItem" align="right_edge">
        Add Item
    </button>

    <!-- Add Item Modal -->
    <div class="modal fade" id="addItem" tabindex="-1" role="dialog" aria-labelledby="addItemLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addItemLabel">Add item specifics</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form method="POST" action="{{ url_for('views.add_item') }}" id="form1">
                        <div class="form-group">
                            <label for="brand">Brand</label>
                            <input type="text" class="form-control" id="brand" name="brand"
                                placeholder="Enter the brand" style="text-transform: capitalize;" />
                        </div>
                        <div class="form-group">
                            <label for="name">Name</label>
                            <input type="text" class="form-control" id="name" name="name" placeholder="Enter the name"
                                style="text-transform: capitalize;" />
                        </div>
                        <div class="form-group">
                            <label for="size">Size</label>
                            <input type="text" class="form-control" id="size" name="size"
                                placeholder="Enter the size" />
                        </div>
                        <div class="form-group">
                            <label for="price">Price</label>
                            <input type="number" min="0.01" step="0.01" max="2500" class="form-control" id="price"
                                name="price" placeholder="Enter the price" />
                        </div>
                        <div class="form-group">
                            <label for="size">Shipping Status</label>
                            <input type="text" class="form-control" id="shippingStatus" name="shippingStatus"
                                placeholder="Enter the shipping status" style="text-transform: capitalize;" />
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <!-- <form action="{{ url_for('views.add_item') }}" method="POST" form="form1"> -->
                            <input class="btn btn-primary" type="submit" value="Add"></input>

                            <!-- <button type="submit" form="form1" name = "add" class="btn btn-primary" data-dismiss="modal">Add item</button> -->
                        </div>
                    </form>
                </div>

            </div>
        </div>
    </div>


</div>
<div class="container">
    <table class="table table-borderless">
        <thead>
            <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Brand</th>
                <th>Name</th>
                <th>Size</th>
                <th>Price</th>
                <th>Shipping Status</th>
                <th>Update</th>
        </thead>
        <tbody>
            {% for item in user.inventory | sort(attribute='id') %}
            <tr>
                <td>{{ item.id }}</td>
                <td>{{ item.date.strftime('%Y-%m-%d') }}</td>
                <td>{{ item.brand.capitalize() }}</td>
                <td>{{ item.name.capitalize() }}</td>
                <td>{{ item.size }}</td>
                <td>{{ item.price }}</td>
                <td>{{ item.shipping_status.capitalize() }}</td>
                <!-- need to access item.id and pass it into function -->
                <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#updateItem"
                        align="right_edge">
                        Update
                    </button>
                    <!-- Update Item Modal -->
                    <div class="modal fade" id="updateItem" tabindex="-1" role="dialog"
                        aria-labelledby="updateItemLabel" aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="updateItemLabel">Update item specifics</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <form method="POST" action="{{ url_for('views.update_item') }}" id="form1">
                                        <input type="hidden" name="item_id" value="{{ item.id }}">
                                        <div class="form-group">
                                            <label for="brand">Brand</label>
                                            <input type="text" class="form-control" id="brand" name="brand"
                                                placeholder="Enter the brand" style="text-transform: capitalize;" />
                                        </div>
                                        <div class="form-group">
                                            <label for="name">Name</label>
                                            <input type="text" class="form-control" id="name" name="name"
                                                placeholder="Enter the name" style="text-transform: capitalize;" />
                                        </div>
                                        <div class="form-group">
                                            <label for="size">Size</label>
                                            <input type="text" class="form-control" id="size" name="size"
                                                placeholder="Enter the size" />
                                        </div>
                                        <div class="form-group">
                                            <label for="price">Price</label>
                                            <input type="number" min="0.01" step="0.01" max="2500" class="form-control"
                                                id="price" name="price" placeholder="Enter the price" />
                                        </div>
                                        <div class="form-group">
                                            <label for="size">Shipping Status</label>
                                            <input type="text" class="form-control" id="shippingStatus"
                                                name="shippingStatus" placeholder="Enter the shipping status"
                                                style="text-transform: capitalize;" />
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary"
                                                data-dismiss="modal">Close</button>
                                            <input class="btn btn-primary" type="submit" value="Update"></input>
                                        </div>
                                    </form>
                                </div>

                            </div>
                        </div>
                    </div>
                </td>


            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
{% endblock %}

标签: pythonhtmlcssflasksqlalchemy

解决方案


推荐阅读