I use the POST
method since I need to change the database. But each time I used the POST
method, this error occurred. Every time I click the button, the page will not be loading and saying "POST /book/go-action/ HTTP/1.1" 405 0
. There is no difference when I use q = request.POST["quantity"]
or q = request.POST.get('quantity', '')
. If I use GET
method, the issue will not occur but the GET
method cannot meet the needs. Also I don't need action
in the form, cos I don't need the page to redirect to somewhere and I'm using ajax to call the function view. How can I fix the issue?
Updated:
The problem was caused by missing action="{% url 'cart:add_to_cart' %}"
. But I don't want it to redirect to another page, that's why I'm using Ajax instead of using action
. If using action
then Ajax will become pointless I guess.
book/detail.html:
<script>
$(document).ready(function () {
$("#add").click(function () {
alert('clicked');
$.ajax({
url: '{% url "cart:add_to_cart" %}',
type: "POST",
dataType: 'json',
success: function (response) {
$("#cartButton").text("Cart" + "(" + response.quantity + ")");
},
error: function (response) {
alert('Got an error');
}
});
});
});
</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>
cart/views.py:
def add_books(request):
c = Cart.objects.get(user=request.user)
if request.method == 'POST':
# q = request.POST["quantity"]
# book_id = request.POST["bookID"]
q = request.POST.get('quantity', '')
book_id = request.POST.get('bookID', '')
# the rest of the code here
return JsonResponse(response)
cart/urls.py:
app_name = 'cart'
urlpatterns = [
path('add_books/', views.add_books, name='add_to_cart')
]
book/urls.py:
app_name = 'book'
urlpatterns = [
path('<slug:slug>/', views.BookDetailView.as_view(), name='detail'),
name='category_search'),
]