我在views.py中有以下视图:
def MoveSucessfulEntries(request):
if request.method == 'POST':
objectsToBeDeleted = request.POST['imagesToBeRemoved']
for objects in objectsToBeDeleted:
print objects
image = Image.objects.get(id=objects)
SucessfulImage(emailAddress=image.emailAddress, image=image.image, caption=image.caption).save()
return render_to_response('images/selectedSucessful.html')
else:
images = Image.objects.all()
return render_to_response('images/deleteUnsucessfulEntries.html', {'images': images})
imagesToBeRemoved
是HTML页面上的复选框,其中包含数据库中图像的ID,其生成方式如下:
<form method="POST" action="/image/selectSucessful">
{% if images %}
{% for image in images %}
<input type="checkbox" name="imagesToBeRemoved" value="{{image.id}}" /> <image src="../media/{{image.image}}"> <br>
{%endfor%}
<input type="submit" value="Select" />
{% else %}
<p>No images are available.</p>
{% endif %}
</form>
所以我知道从表单返回的ids都在数据库中,但我仍然不知道错误对象是否存在。我的代码怎么了?
堆栈跟踪表明错误发生在:
image = Image.objects.get(id=objects)
答案 0 :(得分:2)
问题是你得到一个带
的字符串objectsToBeDeleted = request.POST['imagesToBeRemoved']
由于你要发布多个数据,你想要的是:
objectsToBeDeleted = request.POST.getlist('imagesToBeRemoved')
字符串是可迭代的,所以你迭代每个数字,也就是说,如果你想删除id为345的项目,它实际上会尝试删除id为3,4和5的项目。