【问题标题】:TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'TypeError: int() 参数必须是字符串、类似字节的对象或实数,而不是“NoneType”
【发布时间】:2023-03-10 22:55:01
【问题描述】:

我正在从这个youtube ecommerce tutorial创建一个 django 电子商务网站。我已经创建了一个从购物车中删除的功能,但是当我按下删除按钮时,我收到了这条消息

TypeError at /cart/delete/ int() 参数必须是一个字符串,一个 类似字节的对象或实数,而不是 'NoneType'

这里是函数

def cart_delete(request):
    cart = Cart(request)
    if request.POST.get('action') == 'post':
        product_id = int(request.POST.get('productid'))
        cart.delete(product=product_id)
        response = JsonResponse({'success':True})
        return response

> TypeError at /cart/delete/ int() argument must be a string, a
> bytes-like object or a real number, not 'NoneType' Request
> Method:   POST Request URL:   http://127.0.0.1:8000/cart/delete/ Django
> Version:  3.2.8 Exception Type:   TypeError Exception Value:   int()
> argument must be a string, a bytes-like object or a real number, not
> 'NoneType' Exception
> Location: C:\Users\DELL\Desktop\ecommerce\cart\views.py, line 30, in
> cart_delete Python
> Executable:   C:\Users\DELL\Desktop\ecommerce\venv\scripts\python.exe
> Python Version:   3.10.0

删除函数

def delete(self, product):
        product_id = str(product) 
         
        if product_id in self.cart:
            del self.cart[product_id]
            
        self.session.modified = True 

我的 ajax 脚本

<script>
        $(document).on('click', '#delete-button', function(e){
            e.preventDefault();
            console.log($('#select option:selected').text())
            $.ajax({
                type:'POST',
                url:'{% url "cart:cart_delete" %}',
                data:{
                    productid: $('#add-button').val(),
                    csrfmiddlewaretoken:"{{csrf_token}}",
                    productqty: $('#select option:selected').text(),
                    action: 'post'
                },
                success: function (json){
                     
                },
                error: function (xhr, errmsg, err){}
            })
        })
        
      
    </script>

请帮忙。

【问题讨论】:

  • 您正在使用 NoneType 变量调用删除函数。你能调试一下你在函数参数中设置的内容吗

标签: python json django ajax e-commerce


【解决方案1】:

request.POST 中的 productid 为空。使用$('#add-button').val() 在浏览器控制台中检查该值。

您可以使用in 运算符检查是否存在。


if productid in request.POST:
    product_id = int(request.POST.get('productid'))
    cart.delete(product=product_id)
    response = JsonResponse({'success':True})
else :
    response = JsonResponse({'success': False})


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2018-03-17
    • 2017-07-18
    相关资源
    最近更新 更多