在javascript警报按钮单击后使用ajax更新模型数据-django

pjngdqdw  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(289)

我有一个 javascript 警报(它使用 swal 设置样式,但其功能类似于常规警报)。我想跑步 SomeModel.objects.filter(id=id).delete() 单击“确定”按钮后。我在网上做过研究,我看到很多关于使用的文章 Ajax ,但我真的搞不懂。有人能帮我吗?我的密码在下面。

swal({
  title: "Accept Donation",
  text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?",

  icon: "info",
  buttons: true,

})
.then((ok) => {
  if (ok) {
    swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", {
      icon: "success",

    });
  } 
});
}

views.py:

def acceptdonation(request):
    donations = Donation.objects.all()
    context = {}
    return render(request, 'acceptdonation.html', context)
qjp7pelc

qjp7pelc1#

要通过ajax请求删除模型,您需要:

1.向一个端点发送ajax请求(我将使用fetch api)。

swal({
        title: "Accept Donation",
        text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?",

        icon: "info",
        buttons: true,

      })
      .then((ok) => {
        if (ok) {
          swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", {
            icon: "success",    
          });

          fetch("/endpoint", {
              method:"DELETE",
              headers: {
                  'Content-Type':'application/json'
              },
              body: JSON.stringify({
                  id:"ID_OF_THE_MODEL_INSTANCE"
              })
          })

          // access what the server returns
          .then(data => data.json())
          .then(result => console.log(result))

        } 
      });

2.在该端点的视图中删除对象

基于类的视图:

class DeleteObjectView(TemplateView):

def delete(self, request):
    YourModel.objects.get(pk=request.DELETE['pk']).delete()
    return HttpResponse("item deleted")

基于功能的视图:

def deleteObject(request):
    YourModel.objects.get(pk=request.DELETE['pk']).delete()
    return HttpResponse("item deleted")

如果request.delete querydict对象不存在,只需自己创建即可

DELETE = QueryDict(request.body)

相关问题