【发布时间】:2020-09-06 02:30:36
【问题描述】:
我正在使用 Django 开发一个 Web 应用程序。我正在尝试使用 javascript 中的 post 方法访问 django 中的视图,该方法在单击按钮时调用
我在 Django 模板中使用的 HTML 按钮是
<a id = "{{ f.food_id }}" class="btn btn-info" href="#myModal" onclick="addCart(event);" class="trigger-btn" data-toggle="modal"> Add To Cart</a>
上面的按钮调用下面的java脚本函数
<script>
//This function should call the python function (addToCart) in django views.py which is used to add items to the cart
function addCart(event)
{
var me = event.currentTarget
var food_id = me.getAttribute("id");
alert(food_id);
//The below url "/food/addToCart/(?P<item_id>\d+)" is linked to the addToCart funtion in the views.py
$.post("/food/addToCart/"+food_id+"/", //This post method isn't working
{},
function(data, status){
});
}
</script>
在上面的函数中,我尝试使用上面的 post 方法
在 views.py 中访问下面的 addToCart 方法def addToCart(request,item_id):
try:
cartTrail = Cart.objects.get(user_id=request.user.username,food_id=str(item_id))
cartTrail.quantity += 1
cartTrail.save()
print("already present",cartTrail)
except Cart.DoesNotExist:
items = FoodItem.objects.filter(food_id=item_id)[0]
cartItem = Cart.objects.create(user_id=request.user.username,
res_id=items.restaurant.username.username,
food_id=item_id,food_name=items.food_name,price=items.price)
cartItem.save()
return JsonResponse({'data':'Added'})
我的 urls.py 包含以下网址:
url(r'^addToCart/(?P<item_id>\d+)/$',views.addToCart,name="addToCart"),
我的问题是 post 方法在单击 addToCart 时不起作用,因此 def addToCart(request,item_id): 函数没有被调用。你能建议我哪里出错了
【问题讨论】:
-
可以分享一下你从js调用post请求时得到的错误日志吗?您可能需要在您的帖子数据中发送
csrf_token。 -
@DenizKaplan 我在我的 google chrome 检查控制台中收到错误说明 SCRIPT438: Object does not support property or method 'post'。
标签: django django-rest-framework django-views django-templates