我有一个表单,用于更新我的mongoDB的product_details集合中对象的所有price属性。它就像批量价格更新功能。我尝试了很少但发现很难。 请在django中建议这样做的方法。 如何使用相同的表单和视图更新多个产品的价格?
price.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')
答案 0 :(得分:1)
首先,您的输入字段名称应该是唯一的,您可以使用产品ID作为名称 -
<form class="form-horizontal">
<div class="form-group" >
<label class="control-label col-sm-2" style="padding-top:25px;">test</label>
<div class="col-sm-2 " style="padding-top:20px;">
<select class="form-control">
<option>1</option>
<option>2</option>
</select>
</div>
<div class="col-sm-3">
<select multiple class="form-control">
<option>1</option>
<option>2</option>
</select>
</div>
</div>
</form>
现在,在Django视图中,您可以遍历从表单接收的所有发布数据并更新数据库。这是应该工作的代码 -
<input id="input_text" type="text" name="{{r.object_id}}" value="{{r.price}}" data-length="10">
不要忘记导入ObjectId():
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')
注意:要在Django模板中使用MongoDB ObjectID,您需要一个自定义模板过滤器。请参阅此答案 - https://stackoverflow.com/a/24936772/8039601