Javascript 使用ajax通过复选框从django中的表中删除多条记录

Javascript 使用ajax通过复选框从django中的表中删除多条记录,javascript,html,jquery,django,Javascript,Html,Jquery,Django,我对Django和 我试图在Django应用程序中从一个表中删除多个Lead,但一切正常,除非我尝试在表的字段中执行#select_all复选框,否则控制台中会出现如下错误: jquery-3.6.0.js:10109 POST 500(内部服务器错误) 这是我的密码 视图.py from django.shortcuts import render, reverse, redirect from django.views import generic from django.contrib i

我对Django和 我试图在Django应用程序中从一个表中删除多个Lead,但一切正常,除非我尝试在表的字段中执行#select_all复选框,否则控制台中会出现如下错误:

jquery-3.6.0.js:10109 POST 500(内部服务器错误)

这是我的密码

视图.py

from django.shortcuts import render, reverse, redirect
from django.views import generic
from django.contrib import messages
from .forms import LeadModelForm
from .models import Lead



class LeadCreateView(generic.CreateView):
    model = Lead
    template_name = "leads/lead_create.html"
    form_class = LeadModelForm

    def get_success_url(self):
       return reverse("leads:lead-index")


class LeadUpdateView(generic.UpdateView):
   model = Lead
   template_name = "leads/lead_update.html"
   form_class = LeadModelForm
    
   def get_success_url(self):
     messages.info(self.request, "Lead updated successfully.")
     return reverse("leads:lead-index")


class LeadIndexView(generic.ListView):
   queryset = Lead.objects.all()
   paginate_by = 25
   template_name = "leads/lead_index.html"


def lead_delete(request, pk):
    lead = Lead.objects.get(id=pk)
    lead.delete()
    return redirect("/leads")



class LeadView(generic.View):
    def get(self, request):
        allleads = Lead.objects.all()
        context = {
            'leads': allleads
        }
        return  render(request, "leads/lead_index.html", context)

    def post(self, request, *args, **kwargs):
      if request.method=="POST":
        lead_ids=request.POST.getlist('id[]')
        for id in lead_ids:
            lead = Lead.objects.get(pk=id)
            lead.delete()
        return redirect("/leads")
from django.urls import path
from .views import LeadCreateView, LeadUpdateView, lead_delete, LeadView, LeadIndexView


app_name = "leads"
urlpatterns =[
    path('', LeadIndexView.as_view(), name='lead-index'),
    path('<int:pk>/update/', LeadUpdateView.as_view(), name='lead-update'),
    path('create/', LeadCreateView.as_view(), name='lead-create'),
    path('<int:pk>/delete/', lead_delete, name='lead-delete'),
    path('delete/', LeadView.as_view(), name='delete-multiple'),
]
url.py

from django.shortcuts import render, reverse, redirect
from django.views import generic
from django.contrib import messages
from .forms import LeadModelForm
from .models import Lead



class LeadCreateView(generic.CreateView):
    model = Lead
    template_name = "leads/lead_create.html"
    form_class = LeadModelForm

    def get_success_url(self):
       return reverse("leads:lead-index")


class LeadUpdateView(generic.UpdateView):
   model = Lead
   template_name = "leads/lead_update.html"
   form_class = LeadModelForm
    
   def get_success_url(self):
     messages.info(self.request, "Lead updated successfully.")
     return reverse("leads:lead-index")


class LeadIndexView(generic.ListView):
   queryset = Lead.objects.all()
   paginate_by = 25
   template_name = "leads/lead_index.html"


def lead_delete(request, pk):
    lead = Lead.objects.get(id=pk)
    lead.delete()
    return redirect("/leads")



class LeadView(generic.View):
    def get(self, request):
        allleads = Lead.objects.all()
        context = {
            'leads': allleads
        }
        return  render(request, "leads/lead_index.html", context)

    def post(self, request, *args, **kwargs):
      if request.method=="POST":
        lead_ids=request.POST.getlist('id[]')
        for id in lead_ids:
            lead = Lead.objects.get(pk=id)
            lead.delete()
        return redirect("/leads")
from django.urls import path
from .views import LeadCreateView, LeadUpdateView, lead_delete, LeadView, LeadIndexView


app_name = "leads"
urlpatterns =[
    path('', LeadIndexView.as_view(), name='lead-index'),
    path('<int:pk>/update/', LeadUpdateView.as_view(), name='lead-update'),
    path('create/', LeadCreateView.as_view(), name='lead-create'),
    path('<int:pk>/delete/', lead_delete, name='lead-delete'),
    path('delete/', LeadView.as_view(), name='delete-multiple'),
]
从django.url导入路径
从.views导入LeadCreateView、LeadUpdateView、lead_delete、LeadView、LeadIndexView
app_name=“leads”
URL模式=[
路径(“”,leadinexview.as_view(),name='lead-index'),
路径('/update/',LeadUpdateView.as_view(),name='lead-update'),
路径('create/',LeadCreateView.as_view(),name='lead-create'),
路径('/delete/',lead_delete,name='lead-delete'),
路径('delete/',LeadView.as_view(),name='delete-multiple'),
]
lead_index.html

{% load tailwind_filters %}
{%block content%}
{{form.media}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
      {% block title %}
        leads
      {% endblock title %}
    </title>
</head>
<body><br><br>
    <div class="container container-fluid">
      <div class="page-header">
    <button class="btn btn-lg btn-danger" type="submit" id="delete_btn">
      Delete Selected <i class="fa fa-trash-o" aria-hidden="true"></i>
    </button>
      </div>
    </div>
    <br><br>
    <div class="container">
      <div class="row">
        <table class="table table-hover" id="table">
            <thead class="thead-dark">
                <th scope="col">ID</th>
                <th><input name="site_select_all" value="1" id="select_all" type="checkbox"/></th>
                <th scope="col">Name</th>
                <th scope="col">Phone</th>
                <th scope="col">Mail</th>
                <th scope="col">Source</th>
                <th scope="col">Category</th>
                <th scope="col">User</th>
                <th scope="col">Action</th>
            </thead>
            <tbody class="section">
              {% csrf_token %}
                {% for lead in object_list %}
                <tr id="{{lead.id}}">
                <td>{{lead.id}}</td>
                <td data-th="Select"><input type="checkbox" name="sel" value="{{lead.id}}"></td>
                <td class="col-md-3"><a href="{% url 'leads:lead-update' lead.pk %}">{{ lead.name }}</a></td>
                <td>{{lead.phone}}</td>
                <td>{{lead.email}}</td>
                <td>{{lead.source}}</td>
                <td>{{lead.category}}</td>
                <td>{{lead.user}}</td>
                <td>
                  <a href="{% url 'leads:lead-delete' lead.pk %}" onclick="return confirm('Are you sure you want to delete this Lead?');">
                    <button class="btn btn-danger" id="del">
                      <i class="fa fa-trash-o" aria-hidden="true"></i>
                    </button>
                  </a>
                </td>
                </tr>
                {% endfor %}
            </tbody>
           </table>
          <div>
     </div>
 </div>
<br>
</body>
<script>
  $(document).ready(function(){
  $('#delete_btn').click(function(){
    if(confirm("Are you sure you want to delete selected?"))
    var id = [];
    var csrf = $('input[name=csrfmiddlewaretoken] ').val();
    $(':checkbox:checked').map(function(i){
      id[i]=$(this).val()
    })
    if(id.length===0){
      alert("No leads selected!")
    }
    else{
      $.ajax({
        url:"delete/",
        method: "POST",
        data:{
          id,
          csrfmiddlewaretoken:csrf
        },
        success:function(response){
          for(var i=0; i < id.length; i++){
            $('tr#'+id[i]+'').css('background-color', '#ccc');
            $('tr#'+id[i]+'').fadeOut('slow');
          }
        }
      })
    }
  })
});
$("#select_all").click(function(){
        $("input[type=checkbox]").prop('checked', $(this).prop('checked'));

});
</script>
</html>
{%endblock content%}```


{%load tailwind_filters%}
{%block content%}
{{form.media}
{%block title%}
引导
{%endblock title%}


删除所选内容

身份证件 名称 电话 邮寄 来源 类别 使用者 行动 {%csrf_令牌%} {对象中的潜在客户百分比\列表%} {{lead.id} {{lead.phone}} {{lead.email} {{lead.source}} {{lead.category}} {{lead.user} {%endfor%}
$(文档).ready(函数(){ $('#删除_btn')。单击(函数(){ 如果(确认(“您确定要删除所选内容吗?”)) var id=[]; var csrf=$('input[name=csrfmiddlewaretoken]')。val(); $(':checkbox:checked').map(函数(i){ id[i]=$(this.val() }) 如果(id.length==0){ 警报(“未选择任何潜在客户!”) } 否则{ $.ajax({ url:“删除/”, 方法:“张贴”, 数据:{ 身份证件 csrfmiddlewaretoken:csrf }, 成功:功能(响应){ 对于(变量i=0;i
欢迎使用堆栈溢出!请阅读并回答您的问题,以了解更多详情。当遇到HTTP错误500(字面上是一个内部服务器错误)时,还包括Django应用程序的任何输出(控制台或日志文件中可能有一些输出,因为出现了明显的错误)。这通常是重要信息,有助于我们帮助您。谢谢感谢Alexander的评论,好的,我相信问题是当我尝试使用全选方法从表中删除所有数据时。否则一切都会顺利进行,只要我不点击表格标题中的复选框,我就可以删除任意数量的潜在客户。我猜想selectallonclick函数不会获取其他表行的ID。至于你在我的浏览器的“检查”部分的网络记录中提到的日志,我得到的线索匹配查询不存在。首先,正如我前面所述,请回答你的问题——不要在评论中包含澄清细节!其次,我指的是Django服务器应用程序的输出,而不是浏览器控制台。500表示服务器端出现错误,在浏览器的DevTools中看不到。另外,我不是Django专家,但无意中发现了你的帖子,因此我要求你在问题中包括所有必要的细节,以便任何比我更专业的人来帮助你。啊,好吧,对不起,我弄错了。好的,这是我在服务器端得到的:文件“/home/misen/Downloads/weecrm/venv/lib/python3.8/site packages/django/db/models/query.py”,第435行,在get raise self.model.DoesNotExist(leads.models.Lead.DoesNotExist:Lead matching query不存在。[21/Apr/2021 08:36:13]“POST/leads/delete/HTTP/1.1”500 86083中,如何将您的问题重新定义为包含帮助您所需的详细信息?