我正在创建一个类似捐赠的电子商务网站,允许人们捐赠和出售物品。我有一个名为接受捐赠的屏幕,允许人们查看某项捐赠的详细信息。我在屏幕上有一个按钮,如果用户想要接受捐赠,可以点击这个按钮。单击此按钮时,我会显示一个警报(它使用swal
来设置样式,但功能类似于常规警报),如果用户单击ok
按钮,我想删除他们正在查看的特定数据。我问了this个问题,得到的答案要求我使用id。我并没有在我的模型中分配id,我提供捐赠的方式如下。我想知道如何为我的每一个捐款分配一个唯一的id,以便以后删除它们。我的代码详细如下。另外,请随时提出任何问题,我总是在我的电脑上
Swal警报(我需要分配一个id才能工作):
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) {
// (1) Make a request DELETE to /donations.
return fetch("/donations", {
method: "DELETE",
body: JSON.stringify({
id: "{{donation.id}}" // (2) Include the id and send it as JSON.
})
});
}
})
.then((response) => {
// (3) If response is successful, show the second alert.
if (response.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",
});
}
})
.catch(error => {
console.log(error);
});
捐赠模式:
class Donation(models.Model):
title = models.CharField(max_length=30)
phonenumber = models.CharField(max_length=12)
category = models.CharField(max_length=20)
quantity = models.IntegerField(blank=True, null=True,)
location = models.CharField(max_length=50, blank=True, null=True,)
image = models.ImageField(null = True, blank = True, upload_to = 'images/')
description = models.TextField()
date = models.CharField(blank=True, null=True, max_length=999)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
blank=True,
null=True,
)
基于类的视图,允许我渲染捐赠:
class DonationDetail(DetailView):
model = Donation
queryset = Donation.objects.all()
template_name = 'acceptdonation.html'
与DonationDetail
关联的URL(这会为我的每一个捐赠创建一个自定义URL)
path('donations/<int:pk>/', views.DonationDetail.as_view(), name='donation-detail'),
你的
Donation
模型几乎肯定有一个ID。这是因为模型的默认配置https://docs.djangoproject.com/en/3.2/topics/db/models/#automatic-primary-key-fields事实上,您似乎已经通过/donations/<int:pk>/
使用了它,<int:pk>
参数正在引用ID您的Javascript看起来大致正确,您正在将
{{donation.id}}
放在身体中以指示要删除的捐赠,如上一个问题中所建议的要真正回答这个问题,我们需要知道你的
DELETE
路径在Django land是什么样子的?如果你没有,我就从那里开始顺便说一句,“RESTful”方法是一个
DELETE
请求,而不向/donations/<int:pk>
发送一个主体,其中<int:pk>
是您要删除的捐赠的ID。您所拥有的可能也会起作用,但传统上DELETE
请求没有主体相关问题 更多 >
编程相关推荐