With Pymongo, how do I insert data from a form in the database?
Domanda
I'm trying to do something like this:
info = ([request.form['author'], request.form['title'], request.form['text']])
mongo.db.posts.insert(info, safe=True)
but I get a TypeError:'unicode' object does not support item assignment.
That's the last line in the stack trace:
if not "_id" in son:
son["_id"] = ObjectId()
return son
Soluzione
When using Pymongo your document must be a dict, not list.
Try:
info = {"author": request.form['author'], "title": request.form['title'], "text": request.form['text']}
or:
info = {"info": [request.form['author'], request.form['title'], request.form['text']]}
whatever is closer to your idea of model.
Actually this kind of error is documented for save() and update() methods of collection, but not for insert():
Raises TypeError if to_save is not an instance of dict.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow