P
P
Pavel Dyukarev2018-08-01 20:00:24
Django
Pavel Dyukarev, 2018-08-01 20:00:24

Django2 + Ajax = 404 What's the problem?

Guys, help! Tormented. I don't understand how to make the dispatcher of the second Jungi catch the Ajax request.

The image we click on:

<div id=5 class='selected">
      <img src="{{ charge.img.url }}">
 </div>


We catch Ajax'om:
$(document).ready(function () {

    //    Обновление инфы при клике по карусели
    $(".selected").click(function () {
        var charge_id = $(".selected").attr("id");
        var element = $(this);
        charge_db_update(element);
    });



});


function charge_db_update(element) {
    // сохраним в переменную id заряда
    var charge_id = $(".selected").attr("id");
    //отправляем при помощи ajax: кружок карусели какого товара кликнули?
    $.ajax({
        url: '/charges/get-charge/',
        type: 'GET',
        data: {
            charge_id: charge_id
        }
    })
        .done(function (response){
            console.log("Дошло!");
            $("#info").html(response)
        });

}


Performance:
# обновление инфы при клике по карусели
def get_charge(request):
    charge_id = int(request.GET.get('charge_id', None))

    if charge_id:
        # выбираем заряд из бд по id, получнному из запроса
        charge = Charge.objects.get(id=charge_id)
        response = {
            'charge-answer': charge.answer,
            'charge-question': charge.question,
            'charge-image': charge.img.url
        }
        return HttpResponse(response)


Url dispatcher (first layer):
urlpatterns = [
    path('charges/', include(main_app_urls)),
]

Url dispatcher (second layer):
urlpatterns = [
    # ajax carousel-charge update
    path('get-charge/<int:pk>', views.get_charge),
]


As a result, all the time it turns out:
GET http://127.0.0.1:8000/charges/get-charge/?charge_id=7 404 (Not Found)


Tried a lot of regulars. But they don't all work. Every time I see 404.

This is where I need your advice.
PS Do not send me a link to the documentation - this will not help me - I turned gray while I sat there (rhyme, ep).
It will be better if you write a working template and explain why it is.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-08-01
@PavelDuk

Request parameters are not written in urlpatterns. Or fix the code that sends the request like this

$.ajax({
    url: '/charges/get-charge/' + charge_id,
    type: 'GET'
})

and then get the parameter in the view like so
def get_charge(request, pk):
    charge_id = pk
    ...

or remove it from the pattern
path('get-charge/', views.get_charge),

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question