Home > database >  Ajax URL Not Executing The Correct Function in views.py As Defined in urls.py
Ajax URL Not Executing The Correct Function in views.py As Defined in urls.py

Time:12-07

I am leveraging Ajax for some pie charts but data-ajax-url is not working as intended (or as I thought). Per urls.py, reptibase:item-update should execute the item_update function in my views.py file. item_update never gets executed though and instead the same function associated with the current pages url is executed again.

Currently, am getting a parsing error because HTML is coming back instead of json. json is returned from my item_update function though.

item.js

window.onload = function () {
        console.log("Child: ", document.getElementById("piee"))
        var ctx = document.getElementById("piee").getContext('2d');

        var rep_name = $("#pie1").attr("data-rep-name")
        var ajax_url = $("#pie1").attr('data-ajax-url')
        var _data = []
        var _labels = []

        // Using the core $.ajax() method
        $.ajax({

            // The URL for the request
            url: ajax_url,

            // The data to send (will be converted to a query string)
            data: {
                name: rep_name
            },

            // Whether this is a POST or GET request
            type: "POST",

            // The type of data we expect back
            dataType: "json",

            headers: {'X-CSRFToken': csrftoken},

            context: this
        })
            // Code to run if the request succeeds (is done);
            // The response is passed to the function
            .done(function (json) {

                if (json.success == 'success') {
                    var newMale = json.malePerc
                    var newFemale = json.femalePerc
                    console.log(newMale, newFemale)
                    _labels.push("male", "female")
                    _data.push(parseFloat(newMale), parseFloat(newFemale))
                    window.myPie.update()
                    var newUVB = json.uvbPerc
                    var newSize = json.specSize

                } else {
                    alert("Error: "   json.error);
                }
            })
            // Code to run if the request fails; the raw request and
            // status codes are passed to the function
            .fail(function (xhr, status, errorThrown) {
                alert("Sorry, there was a problem!");
                console.log("Error: "   errorThrown);
                console.log("Status: "   status);
                console.dir(xhr);
                console.warn(xhr.responseText)
            })
            // Code to run regardless of success or failure;
            .always(function (xhr, status) {
                //alert("The request is complete!");
            });

        var config = {
            type: 'pie',
            data: {
                datasets: [{
                    data: _data,
                    backgroundColor: ['#ff0000', "#0000ff"],
                    label: "Temp"
                }],
                labels: _labels,
            },
            options: {
                responsive: true
            }
        };

        console.log("data", _data);
        console.log("config", config)
        window.myPie = new Chart(ctx, config);
        console.log("window", window.myPie)
    }

urls.py

app_name = 'reptibase'
urlpatterns = [
    path('', views.index, name='home'),
    path('search', views.reptile_search, name='search'),
    path('add', views.reptile_add, name='add'),
    path('list', views.reptile_list, name='list'),
    path('listD', views.reptile_listDelete, name='listDelete'),
    #path('<int:rep_id>', views.reptile_item, name='item'),
    path('<str:scientific>', views.reptile_itemAlt, name='itemAlt'),
    path('<int:rep_id>,<int:specific_id>', views.reptile_itemAlt_Edit, name='itemAltEdit'),
    path('<str:reptile>,<int:id>', views.comments, name='comments'),
    path('update', views.item_update, name='item-update'),
    path('edit', views.reptile_edit, name='edit'),
]

itemAlt.html

<div class="pie-chart" id="pie1" data-rep-name="{{ reptile.scientific }}"
     data-ajax-url="{% url "reptibase:item-update" %}">
    <canvas id="piee"></canvas>
    <div class="graph-popout">
        <div class="data">
            <p>{{ femalePerc }}% Female, {{ malePerc }}% Male. {{ size }} Individuals</p>
        </div>
        <p><a href="#">Report Issue</a></p>
        <p><a href="#" class="share">Share</a></p>
    </div>
    <h3>Sex</h3>
    <div class="background"></div>
    <div id="slice1" class="pie-slice">
        <div class="pie"></div>
    </div>
    <div id="slice2" class="pie-slice">
        <div class="pie"></div>
    </div>
    <div id="slice3" class="pie-slice">
        <div class="pie"></div>
    </div>
</div>

CodePudding user response:

path('<str:scientific>', views.reptile_itemAlt, name='itemAlt'),

is likely going to be matching against the requests which you want to go to:

path('update', views.item_update, name='item-update'),

and by extension the edit endpoint below that!

Move 'item-update'(reptibase/update) and 'edit'(repitbase/edit) above 'itemAlt' to account for their respective paths and then all other requests should pass through those and get captured by the correct view.

See the section entitled 'The Path Before Us' here, which gives a good explanation of this phenomenon:

https://www.mattlayman.com/understand-django/urls-lead-way/

  • Related