简体   繁体   中英

MongoDB - Python Flask problem: AttributeError: 'Cursor' object has no attribute 'title'

im doing a simple Flask-MongoDB CRUD application but i keep getting the error message AttributeError: 'Cursor' object has no attribute 'title' for my show route.

db = mongo.db
products_collection = db.products


@app.route("/product/<product_title>")
def product(product_title):
    product =  products_collection.find({"title": product_title})
    return render_template('product.html', title=product.title, product=product)

Where in my DB the products have a title field.

I belive that the problem is in the "product.title" where it isn't acessing the title through the product variable

You need to define an iteration on product to get a list of documents from collection.

@app.route("/product/<product_title>")
def product(product_title):
    products =  products_collection.find({"title": product_title})
    result = []
    for i in products :
        result.append(i)
    p = result[0] 
    #since result is a list you need to specify index, pay attention to this part, if more 
    #than one document is retrieved from collection others will be ignored.
    return render_template('product.html', title=p.title, product=p)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM