Python Forum
insert more data at once in MongoDB - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: insert more data at once in MongoDB (/thread-28100.html)



insert more data at once in MongoDB - Leon79 - Jul-05-2020

Hello Coders!

I'm trying to upload data with Python to MongoDB from a form in HTML.

I can do it with no problem if I upload only the form, but I don't know how to add additional values to the same submission, I get errors. I show you my code:

@app.route('/insert_recipe', methods=['POST'])
def insert_recipe():
    recipes = mongo.db.recipes
    
    x = datetime.datetime.now()
    posted = x.strftime("%d") + " " + x.strftime("%b")  + " " + x.strftime("%Y")
    
    
    date_post = {
        "posted" : posted
    }
    

    recipes.insert_one(request.form.to_dict(), posted)


    
    if request.files:

        image = request.files["picture"]

        path = os.getcwd()
        image_dir = path + "/static/images/" + image.filename
        
        image.save(image_dir)

    # Once that's done, we redirect to recipe.html, so we can view the new recipe in our collection.
    return redirect(url_for('index'))
As you can see request.form.to_dict() is all the data coming from the form, and posted is an additional value that I would like to add. It's important for me to know how to do it, but this doesn't work, I can only manage to upload the form if I leave the code simply with:

    recipes = mongo.db.recipes
    recipes.insert_one(request.form.to_dict())
Second thing I would like to rename the image with the Object ID that the submission creates, is this possible?

Thank you very much! I'm a beginner then forgive my stupid question.

Thank you!


RE: insert more data at once in MongoDB - ndc85430 - Jul-05-2020

Why don't you combine the two dictionaries? You might want to look at the update method of the dict class if you want to use something built in (the third party library Toolz has a function called merge also).


RE: insert more data at once in MongoDB - Leon79 - Jul-05-2020

Thank you very much, I solved adding a value to the dictionary:

    dict1 = request.form.to_dict()
    dict1['posted'] = posted

    recipes.insert_one(dict1)
Now I just need to understand how to get the objectID and rename the picture with the objectID value.