简体   繁体   中英

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

I'm using Ajax to post data. It threw the error 403 (Forbidden), then I added @csrf_exempt to my view. Afterwards, error 500 (Internal Server Error) occurred. 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. So I don't it's the problem of the view I reckon.

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.

cart/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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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