【问题标题】:Error while calling a Post method in Django templates在 Django 模板中调用 Post 方法时出错
【发布时间】: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


【解决方案1】:

你应该在你的 post 请求中传递 csrf_token 否则它会被服务器拒绝 这里是docs 的一部分,它谈到了这一点 如果您想解决 csrf 验证问题,可以将此装饰器添加到您的视图中

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def addToCart(request,item_id):
  // the rest of the view

【讨论】:

  • 我仍然收到同样的错误,指出“SCRIPT438:对象不支持我的 google chrome 检查控制台中的属性或方法 'post'”。
  • okey 那么为什么在您在 url 中传递 id 时使用 post 请求,您可以将其更改为 no ?
  • 我尝试使用 get 但仍然有错误提示“TypeError: $.get is not a function”
  • 尝试将 $.get 更改为 jQuery.get
  • 感谢您的帮助!!我使用的是 jQuery 的 SLIM 版本,所以它不起作用,
猜你喜欢
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 2020-04-10
  • 2012-12-29
  • 1970-01-01
  • 2014-04-06
  • 2021-02-28
相关资源
最近更新 更多