简体   繁体   English

如何仅在用户登录时运行 ajax。(Django)

[英]How to run ajax only when user is logged in. (Django)

I've multiple items that can be added to the cart by clicking the respective button.我有多个可以通过单击相应按钮添加到购物车的项目。 Each item is a form having information about itemid and, the 'addtocart' button is the submit button for the form.每个项目都是一个包含有关 itemid 信息的表单,“addtocart”按钮是表单的提交按钮。

I'm using ajax to make changes in the DB and then reload the page to reflect them.我正在使用 ajax 在数据库中进行更改,然后重新加载页面以反映它们。

Html Html

<script type="text/javascript">

    $(document).on('submit','.addtocart',function(e){

        e.preventDefault();
        var a=$(this).find('input[name=itemid]').val();

        $.ajax({              

          type:'POST',
          url:'addtocart',
          data:{
            itemid:a,
            'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val()
          }
          });
          setTimeout(() => { document.location.reload(true);} , 100);


    });
</script>

views.py视图.py

@login_required(login_url='/userhome')
def addtocart(request):
    if request.method == "GET":
        return redirect('/')
    else:

        product_id = request.POST['itemid']
        product_quantity = 1
        cart = usercart.objects.all().filter(user_id = request.user.id, product_id = product_id )
        try:
            if cart[0] is not None:
                cart = usercart.objects.get(user_id = request.user.id, product_id=product_id)
                cart.product_quantity+=1
                cart.save()

            else:
                cart = usercart(product_id=product_id, user_id=request.user.id, product_quantity=product_quantity)
                cart.save()
        except IndexError:
                cart = usercart(product_id=product_id, user_id=request.user.id, product_quantity=product_quantity)
                cart.save()
        return redirect('checkout')

I want to redirect to the login page ('/userhome') if the user is not logged in and addtocart button is clicked.如果用户未登录并且单击了 addtocart 按钮,我想重定向到登录页面('/userhome')。 I've tried wrapping my Js inside我试过把我的 Js 包在里面

{% if user.is_authenticated %} 
  <script>
  ...
  </script>
{% endif %}

But due to this, the user cannot see the products before logging in. I want a user to see products without logging but addtocart button should work in both situations, redirecting to users who are not logged in and adding products for the user who are logged in.但由于这个原因,用户在登录之前看不到产品。我希望用户在没有登录的情况下看到产品,但 addtocart 按钮应该在这两种情况下都有效,重定向到未登录的用户并为登录的用户添加产品在。

You should use the statusCode callbacks for your ajax method.您应该为您的ajax方法使用statusCode回调。 This will also prevent any issues where the POST request takes longer than 100ms and the page is reloaded before the database is updated.这也将防止 POST 请求花费超过 100 毫秒并且在更新数据库之前重新加载页面的任何问题。

You are also returning a redirect in the request to the checkout page, ajax requests should not recieve redirect responses usually.您还在结帐页面的请求中返回重定向,ajax 请求通常不应收到重定向响应。 You should instead return a success status code, here I use http responses, but JSON responses would be better.您应该返回一个成功状态码,这里我使用 http 响应,但 JSON 响应会更好。

return HttpResponse("", status=200)

If the user is not logged in return a response code associated with being unauthorised如果用户未登录,则返回与未经授权相关的响应代码

return HttpResponse("", status=401)

Use the above methods instead of using the @login_required decorator as it will return a redirect.使用上述方法而不是使用@login_required装饰器,因为它将返回重定向。

You can then handle this in the ajax method using the statusCode callbacks:然后,您可以使用statusCode回调在 ajax 方法中处理此问题:

$.ajax({              
    type:'POST',
    url:'addtocart',
    data:{
        itemid:a,
        'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val()
    },
    statusCode: {
        200: function() {
            // Success! Reload the page
            document.location.reload(true);
        },
        401: function() {
            // Unauthorized, redirect to home
            window.location.href = "/userhome";
        },
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM