[英]Getting Error while deleting Cart item using DestroyAPIView with Javascript. (Django)
I'm using DestroyAPIView with Javascript to delete the cart item in Django我正在使用带有 Javascript 的DestroyAPIView来删除 Django 中的购物车项目
While clicking on delete button it shows the following error on chrome console
:单击删除按钮时,它在chrome
console
上显示以下错误:
jquery.min.js:2 DELETE http://127.0.0.1:8000/showdata/2342; 404 (Not Found)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
destoryCart @ (index):46
onclick @ (index):1
(index):55 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
and in vs code terminal
showing:并在vs 代码
terminal
显示:
Not Found: /showdata/2342;
and all my code goes here:我所有的代码都在这里:
views.py视图.py
class CartDestroyAPIView(DestroyAPIView): # DeleteView
permission_classes = [IsAuthenticated] # Or anything else you want
authentication_classes = [SessionAuthentication] # Or anything else you want
serializer_class = productserializers
queryset = Cart.objects.all()
index.html索引.html
<script>
$(document).ready(function() {
$.ajax({
url: 'http://127.0.0.1:8000/showdata ',
dataType: 'JSON',
success: function(data){
for (var i = 0; i < data.length; i++)
{
var row =
$('<tr><td style="font-style:bold">'
+data[i].product.name+'</td><td style="font-style:bold">'
+data[i].product.price+'</td><td><a href='
+data[i].product.link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><button onclick="destoryCart('+data[i].product.id+')" type="button" class="btn btn-outline-danger">DELETE</button></td></tr>');
$("#tableProduct").append(row);
}
}
});
});
const destoryCart = (id) => {
let url = `http://127.0.0.1:8000/showdata/${id};`
$.ajax({
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRFToken', "{{ csrf_token }}");
},
url: url,
type: 'DELETE',
success: (data) => {
console.log("deleted!");
},
error: (err) => {
console.log(err);
}
});
};
</script>
urls.py网址.py
path('cart_destroy/<int:pk>', views.CartDestroyAPIView.as_view(), name ='cart_destroy'),
WHAT IS WRONG GOING WITH THIS CODE.这段代码出了什么问题。
Change your URL in ajax call you have to put this URL in side your destoryCart()
在 ajax 调用中更改您的 URL 调用,您必须将此 URL 放入您的
destoryCart()
let url = `http://127.0.0.1:8000/cart_destroy/${id};`
instead of this URL
http://127.0.0.1:8000/showdata/${id};
而不是这个
URL
http://127.0.0.1:8000/showdata/${id};
UPDATE更新
get csrf_token
like this i don't know if there is another way but as per official doc .像这样获取
csrf_token
我不知道是否有其他方法,但根据官方文档。
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
And you ajax
call和你
ajax
通话
const destoryCart = (id) => {
$.ajax({
type: 'POST',
url: "{% url 'cart_destroy' %}",
data: {
'product_id': id,
'csrfmiddlewaretoken': csrftoken,
},
success: function(success) {
console.log('success : '+success.responseText)
},
error: function(error) {
console.log('error : '+error.responseText)
},
});
}
and you have to update your URL
also like this你也必须像这样更新你的
URL
path('cart_destroy/', views.CartDestroyView, name ='cart_destroy'),
add this in your views.py
在你的
views.py
中添加这个
def CartDestroyView(request):
if request.method == "POST":
product_id = request.POST['product_id']
Cart.objects.filter(id=product_id).delete()
return HttpResponse({'Success':"Deleted Successfully."})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.