patrickdarya
patrickdarya

Reputation: 35

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

Upvotes: 1

Views: 1674

Answers (1)

Pouya Esmaeili
Pouya Esmaeili

Reputation: 1261

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)

Upvotes: 1

Related Questions