我需要帮助编写一个获取POST数据的视图,然后找出已检查的复选框,然后从id匹配的数据库中删除项目。 最初,这是一个复选框问题。在编辑订单表单中,有一个项目列表。现在我可以使用一些javascript删除该项目,但它没有得到保存,因为我需要从我的数据库完全删除它。我尝试使用我的编辑订单视图使用delete()删除项目,但这不起作用。一定有别的我做错了,但我不知道是什么。
delete_item = request.POST.get('delete_item', None)
if request.method == 'POST':
form = forms.OrderForm(request.POST, instance = order)
if form.is_valid() and save_item is not None:
form.save(True)
request.user.message_set.create(message = "The order has been updated successfully.")
return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")
if status is not None and contact is not None and save_status is not None and delete_item is not None:
try:
for id in status_items:
item = models.StorageItem.objects.get(pk = id)
delete = item
delete.delete()
current_status = models.ItemStatusHistory(item = item, contact = contact, status = status,
user = request.user)
current_status.save()
except:
pass
request.user.message_set.create(message = "Status successfully changed for {0} items".format(len(status_items)))
{% for item in items %}
<tr class="items_table_row">
<td><input type="checkbox" name="item" value="{{item.pk}}" checked="checked"{% endif %}>
<td>{{item.tiptop_id}}</td><td>{{item.alternative_id}}</td><td>{{item.title}}</td><td>{{item.type}}</td><td>{{item.format}}</td>
<td><span id="{{item.pk}}" name="type">{{item.itemstatushistory_set.latest}}</span></td><td>{{item.itemstatushistory_set.latest.date.date|date:"d M Y"}}</td>
<td><a href="{% url tiptop.views.edit_item item.client.pk item.pk %}" onclick="return showAddAnotherPopup(this);">Edit</a></td>
</tr>
{% endfor %}
答案 0 :(得分:5)
鉴于您的模板使用name="item"
复选框... ... .delete()应该有效。
Items.objects.filter(id__in=request.POST.getlist('items')).delete()
你得到例外吗? delete()
代码是否一直在运行?扔一份印刷声明。
你有“大量的代码”,我们不熟悉的很多条件,以及try / except块,所以我只想确保视图实际上是在删除阶段。
更新:这是您的代码陌生人应遵循的一段粗略代码。
if status is not None and contact is not None and save_status is not None and delete_item is not None:
为什么不检查是否存在按下的特定按钮?
# html
<input type="submit" name="save" value="Save Items" />
<input type="submit" name="delete" value="Delete Items" />
# view
if request.POST.get('delete'):
Items.objects.filter(id__in=request.POST.getlist('items')).delete()
elif request.POST.get('save'):
form = Form(request.POST)
# ... so on