Python Django和Pymongo-获取多个输入并更新所有对象中的单个字段 使用用户输入更新django mongodb中的多个文档
我有一个表单,用于更新我的mongoDB的product_details集合中对象的所有价格属性。它类似于批量价格更新功能。我尝试了一些,但发现很难。 请建议在django中执行此操作的方法。 如何使用相同的表单和视图更新多个产品的价格? price.htmlPython Django和Pymongo-获取多个输入并更新所有对象中的单个字段 使用用户输入更新django mongodb中的多个文档,python,html,django,django-forms,pymongo,Python,Html,Django,Django Forms,Pymongo,我有一个表单,用于更新我的mongoDB的product_details集合中对象的所有价格属性。它类似于批量价格更新功能。我尝试了一些,但发现很难。 请建议在django中执行此操作的方法。 如何使用相同的表单和视图更新多个产品的价格? price.html <form class="col s12" action="{% url "bulk" %}" method="POST">{% csrf_token %} <button class="btn waves-
<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>
产品详细信息对象的mongoDB结构
首先,您的输入字段名称应该是唯一的,您可以使用产品id作为名称-
<input id="input_text" type="text" name="{{r.object_id}}" value="{{r.price}}" data-length="10">
不要忘记导入ObjectId():
注意:要在Django模板中使用MongoDB ObjectID,您需要一个自定义模板过滤器。参考这个答案-Thanx dude。。。。它工作得非常好。。。请给他100个名声。
<input id="input_text" type="text" name="{{r.object_id}}" value="{{r.price}}" data-length="10">
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')
from bson.objectid import ObjectId