Javascript 如何在ListView中的Django中执行.delete()查询集?
以下是我迄今为止所做的工作: 1.)我制作了一个javascript函数,可以像这样获取数据库中所有项目的id(使用复选框select)(这是DataTables):Javascript 如何在ListView中的Django中执行.delete()查询集?,javascript,django,datatables,django-class-based-views,Javascript,Django,Datatables,Django Class Based Views,以下是我迄今为止所做的工作: 1.)我制作了一个javascript函数,可以像这样获取数据库中所有项目的id(使用复选框select)(这是DataTables): 函数(){ //计数检查用于检查所选项目。 var count=table.rows({selected:true}).count(); //数一数。 //计数必须大于0才能删除项目。 //如果countYes,您可以使用linked example.Django Admin以相同的方式发送选定ID,Django根据给定值进行筛选
函数(){
//计数检查用于检查所选项目。
var count=table.rows({selected:true}).count();
//数一数。
//计数必须大于0才能删除项目。
//如果countYes,您可以使用linked example.Django Admin以相同的方式发送选定ID,Django根据给定值进行筛选,然后在Django为选定项目应用选定操作
更新
比如说
class List(ListView);
def post(self, request, *args, **kwargs):
ids = self.request.POST.get('ids', "")
# ids if string like "1,2,3,4"
ids = ids.split(",")
try:
# Check ids are valid numbers
ids = map(int, ids)
except ValueError as e:
return JsonResponse(status=400)
# delete items
self.model.objects.filter(id__in=ids).delete()
return JsonResponse({"status": "ok"}, status=204)
和html:
<button id="delete-button">Del</button>
<div id="items-table">
{% for object in objects_list %}
<div class="item" data-id="{{object.id}}">{{ object.name }}</div>
{% endfor %}
</div>
<script>
$(function(){
$('#delete-button').on('click', function(e) {
// Get selected items. You should update it according to your template structure.
var ids = $.map($('#items-table item'), function(item) {
return $(item).data('id')
}).join(',');
$.ajax({
type: 'POST',
url: window.location.href ,
data: {'ids': ids},
success: function (res) {
// Update page
window.location.href = window.location.href;
},
error: function () {
// Display message or something else
}
});
})
})();
</script>
Del
{对象中对象的%u列表%}
{{object.name}
{%endfor%}
$(函数(){
$(“#删除按钮”)。在('click',函数(e){
//获取所选项目。应根据模板结构进行更新。
变量ID=$.map($('#items表项'),函数(项){
返回$(项).data('id'))
})。加入(‘,’);
$.ajax({
键入:“POST”,
url:window.location.href,
数据:{'ids':ids},
成功:功能(res){
//更新页面
window.location.href=window.location.href;
},
错误:函数(){
//显示消息或其他东西
}
});
})
})();
我该怎么做?你能教我一个循序渐进的例子吗?我正在使用一个基于类的ListView和一个DataTables按钮函数,如上所示。@Kenny查看更新后的答案。我附上了一个简单的例子。非常感谢!这是一个很大的帮助。现在我正在根据我的结构编辑你的代码。希望我能把它带到工作。等一下。再次谢谢你!
<button id="delete-button">Del</button>
<div id="items-table">
{% for object in objects_list %}
<div class="item" data-id="{{object.id}}">{{ object.name }}</div>
{% endfor %}
</div>
<script>
$(function(){
$('#delete-button').on('click', function(e) {
// Get selected items. You should update it according to your template structure.
var ids = $.map($('#items-table item'), function(item) {
return $(item).data('id')
}).join(',');
$.ajax({
type: 'POST',
url: window.location.href ,
data: {'ids': ids},
success: function (res) {
// Update page
window.location.href = window.location.href;
},
error: function () {
// Display message or something else
}
});
})
})();
</script>