简体   繁体   中英

Django - POST method error "POST /......./ HTTP/1.1" 405 0 with Ajax

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'),
]

The issue is that your form submits and sends the request to /book/go-action/ , which I assume is the route for the view the form is on, but the route that the POST should go to is /add_books as defined in your urls.py .

To fix this, you need to add an action attribute to your <form> . Here's an example:

<form method="post" action="/add_books"> {% 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>

Edit : Ajax Code (independent of my above code)

I think the main issue here is that while the click event function will work properly (as far as I can tell), after it executes, the submit event is still triggered and the default action ensues. To fix you need to add event as an argument to the function and call preventDefault on that event so that the default submit does not happen.

Here's what that looks like:

<script>
    $(document).ready(function () {
        $("#add").click(function (event) {
            event.preventDefault();
            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>

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