简体   繁体   English

Django-Ajax POST错误403(禁止)和500(内部服务器错误)

[英]Django - Ajax POST error 403 (Forbidden) and 500 (Internal Server Error)

I'm using Ajax to post data. 我正在使用Ajax发布数据。 It threw the error 403 (Forbidden), then I added @csrf_exempt to my view. 它引发了错误403(禁止),然后我在视图中添加了@csrf_exempt Afterwards, error 500 (Internal Server Error) occurred. 此后,发生错误500(内部服务器错误)。 I've tried different like following the docuement to add extra code and imported it to the template. 我尝试了不同的操作,例如按照文档添加额外的代码并将其导入模板。 I'm struggling to fix these two problem. 我正在努力解决这两个问题。 One's gone then the other occurs. 一个人走了,然后另一个人发生了。

Also the view works fine using action attribute rather than Ajax. 而且,使用action属性而不是Ajax可以使视图正常工作。 So I don't it's the problem of the view I reckon. 所以我不是我认为的观点问题。

detail.html: detail.html:

<script>
    $(document).ready(function () {
        $("#add").click(function (event) {
            event.preventDefault();
            $.ajax({
                url: '{% url "cart:add_to_cart" %}',
                type: "POST",
                dataType: 'json',

                success: function (response_data) {
                    alert('second alert');
                    $("#cartButton").text("Cart" + "(" + response_data.quantity + ")");
                },
            });
        });
    });

</script>

<form method="post">
    {% csrf_token %}
    <select name="quantity">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
    <input name="bookID" value=" {{ book.id }} " hidden>
    <button id="add" type="submit"> Add to Cart</button>
</form>

Once I added @csrf_exempt , error 500 came out. 添加@csrf_exempt ,就会出现错误500。

cart/views.py: 车/ views.py:

@csrf_exempt
def add_books(request):
    print('submitted')
    c = Cart.objects.get(user=request.user)

    if request.method == 'POST':
        q = request.POST.get('quantity', )
        book_id = request.POST.get('bookID', )

        the_id = int(book_id)
        the_quantity = int(q)
        b = Book.objects.get(id=the_id)
        c = Cart.objects.get(user=request.user)
        title = b.title

        book = BooksInCart.objects.filter(cart=c).filter(book__title=title)
        if book:
            book_in_cart = book.get(book__title=title)
            book_in_cart.quantity += the_quantity
            book_in_cart.save()
        else:
            book_in_cart = BooksInCart.objects.create(cart=c, book=b, quantity=the_quantity)
            book_in_cart.save()

        response_data = {
            'quantity': BooksInCart.objects.filter(cart=c).aggregate(item_quantity=Sum('quantity'))['item_quantity']
        }
        return JsonResponse(response_data)

part of the error info: 错误信息的一部分:

"ValueError at /cart/add_books/↵invalid literal for int() with base 10: ''↵↵Request Method: POST↵Request URL: http://127.0.0.1:8000/cart/add_books/↵Django Version: 2.1
q = request.POST.get('quantity', ) # <--- this or
book_id = request.POST.get('bookID', ) # <---- this is coming back as an empty string
# The below code is causing an error because the above code isn't finding anything
# And it is returning to you an empty string, which it cannot convert to an int()
the_id = int(book_id)
the_quantity = int(q)

You need to make sure that there is a value coming back in your POST request otherwise, you'll continue to have the problem of the empty string. 您需要确保POST请求中返回一个值,否则,您将继续遇到空字符串的问题。 If you are requiring that value, you could require that value before the user can POST the form or you could throw an error in the validation on the server. 如果需要该值,则可以在用户可以过帐表单之前要求该值,否则可能会在服务器上的验证中引发错误。

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

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