python - Django 和 Pymongo - 获取多个输入并更新所有对象中的单个字段

标签 python html django django-forms pymongo

使用用户输入更新 django-mongodb 中的多个文档

我有一个表单,旨在更新我的mongoDB的product_details集合中对象的所有价格属性。它就像批量价格更新功能。我尝试了一些,但发现很难。 请建议在 django 中执行此操作的方法。 如何使用相同的表单和 View 更新多个产品的价格?

enter image description here

价格.html

 <form class="col s12" action="{% url "bulk" %}" method="POST">{% csrf_token %}
    <button class="btn waves-effect waves-light" type="submit" name="action">Update<i class="material-icons right">cloud</i>
  </button>
    {% for r in result %} 



               <div class="col s6 m7">
                  <div class="card horizontal">
                    <div class="card-image"  >
                      <img class ="materialboxed" width="650" src="{{r.ppro}}" style="width:100px;
                 height:150px;
                 max-width:100%;
              max-height:100%;" >
                    </div>
                    <div class="card-stacked">
                      <div class="card-content">
                        <p style="font-size:15px;">{{r.ptitle}}<br>{{r.price}}</p>
                      </div>
                      <div class="card-action">

                        <div class="input-field col s4">
                          <input id="input_text" type="text" name=price  value="{{r.price}}"  data-length="10">
                          <label for="input_text">Price</label>
                        </div>



                      </div>
                    </div>
                  </div>
                </div>


{% endfor %}


</form>

  </div>
<小时/>

views.py

def bulk_price(request):


    product_list= user_db.product_details.find({"shop_id":request.session["_id"]})
    user_data = user_db.store_details.find_one({"_id":request.session["_id"]})

    if product_list is not None:
            return render(request,'price.html',{'result':product_list,'status':user_data['status']})
    return render(request,'price.html')

product_details对象的mongoDB结构 enter image description here

最佳答案

首先,您输入的字段名称应该是唯一的,您可以使用产品 ID 作为名称 -

<input id="input_text" type="text" name="{{r.object_id}}"  value="{{r.price}}"  data-length="10">

现在,在 Django View 中,您可以迭代从表单接收的所有发布数据并更新数据库。这是应该有效的代码 -

def bulk_price(request):
    #If request method is POST, update the database 
    if request.method == "POST":
        for key in request.POST: #Iterate through POST variables
            value = request.POST[key]
            try:
                objectId = ObjectId(key)
            except Exeption as e:
                #The key is not a valid object id, it might be csrfmiddlewaretoken or some other post data
                continue
            user_db.product_details.update_one(
                    {'_id': objectId},
                    {'$set': {'price': value}}, 
                    upsert=False
                )

    #Render the update price page         
    product_list= user_db.product_details.find({"shop_id":request.session["_id"]})
    user_data = user_db.store_details.find_one({"_id":request.session["_id"]})
    if product_list is not None:
            return render(request,'price.html',{'result':product_list,'status':user_data['status']})
    return render(request,'price.html')

不要忘记导入 ObjectId():

from bson.objectid import ObjectId

注意:要在 Django 模板中使用 MongoDB ObjectID,您将需要一个自定义模板过滤器。引用这个答案-https://stackoverflow.com/a/24936772/8039601

关于python - Django 和 Pymongo - 获取多个输入并更新所有对象中的单个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44647901/

相关文章:

python - Django模拟通过命令行连接的用户

python - 查找旧项目的 django 版本号

python - 如何转换 datetime.strptime() 奇怪的日期格式(其中包含单词 "of")?

python - 取消引用 numpy 数组或列表的 void 指针

python - 易于在 Python 中使用时间戳

Javascript:showDiv 添加 anchor #top

html 布局问题 : how to achieve this layout?

html - CakePHP 图像未调整大小,适合容器

python - Django 模型类中的多态性

python - 更改 Django 设置后 uwsgi 不会重新加载