Home > Blockchain >  how to update mongodb using button in html, pymongo
how to update mongodb using button in html, pymongo

Time:12-04

I have a base.html that has items, and button for user to click.

                                <p class="card-text">{{data[0].name}}</p>
                                <div class="d-flex justify-content-between align-items-center">
                                <div class="btn-group">
                                    <form action="/update/<%= data[0]._id %>" method="PATCH">
                                    <p style="margin-right:5px;">Available: {{data[0].inventory}}</p>
                                    <button type="button" class="btn btn-sm btn-outline-secondary">Add to cart</button>
                                    </form>
                                </div>

And I have hello.py python file that runs the server.

from flask import Flask, render_template, redirect, request, url_for
from pymongo import MongoClient
from bson.objectid import ObjectId
app = Flask(__name__)
 

@app.route('/',methods=['GET'])
def mongoTest():
    client = MongoClient('mongodb://localhost:27017/')
    db = client.ecommerce
    collection = db.items
    results = collection.find()
    # client.close()
    return render_template('base.html', data=results)


@app.route("/update/:id", methods=["PATCH"])
def update_inventory(id):    
    client = MongoClient('mongodb://localhost:27017/')
    db = client.ecommerce
    id=request.values.get("_id")    
    db.items.update_one({ '_id': id}, {'$inc': {'inventory': -1}}, upsert=False)
    results2 = db.items.find()
    return render_template('base.html', data=results2)

if __name__ == '__main__':
    app.run(debug=True)

However, it does not update the inventory values. How do I solve this problem?

CodePudding user response:

Is the id a string? if so it needs to be transformed into an ObjectId. (in most cases, you let mongo handle ids, so ids are ObjectId, not strings).

from bson.objectid import ObjectId

@app.route("/update/:id", methods=["PATCH"])
def update_inventory(id):    
    client = MongoClient('mongodb://localhost:27017/')
    db = client.ecommerce
    id = ObjectId(request.values.get("_id"))
    db.items.update_one({ '_id': id}, {'$inc': {'inventory': -1}}, upsert=False)
    results2 = db.items.find()
    return render_template('base.html', data=results2)

Otherwise, you have to check:

  • if the id exists, if not return an error?
  • "items" collection doest exist? (not Item nor item?)
  • Related