我正在使用Ajax发布数据。它引发了错误403(禁止),然后我在视图中添加了@csrf_exempt
。此后,发生错误500(内部服务器错误)。
我尝试了不同的操作,例如遵循docuement添加额外的代码并将其导入模板。我正在努力解决这两个问题。一个人走了,然后另一个人发生了。
此外,使用action
属性而不是Ajax可以使视图正常工作。所以我不是我认为的观点问题。
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>
一旦我添加了@csrf_exempt
,就会出现错误500。
购物车/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)
部分错误信息:
"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
答案 0 :(得分: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)
您需要确保POST请求中返回一个值,否则,您将继续遇到空字符串的问题。如果需要该值,则可以在用户发布该表单之前要求该值,否则可能会在服务器上的验证中引发错误。